<?php

namespace FluxBB\Markdown\Parser;

use FluxBB\Markdown\Common\Text;
use FluxBB\Markdown\Node\Heading;

class SetextHeaderParser extends AbstractParser
{

    /**
     * Parse the given block content.
     *
     * Any newly created nodes should be pushed to the stack. Any remaining content should be passed to the next parser
     * in the chain.
     *
     * @param Text $block
     * @return void
     */
    public function parseBlock(Text $block)
    {
        $block->handle(
            '{^(.+)[ \t]*\n(=+|-+)[ \t]*\n+}m',
            function (Text $whole, Text $content, Text $mark) {
                $level = (substr($mark, 0, 1) == '=') ? 1 : 2;

                // TODO: Parse content as inline.

                $this->stack->acceptHeading(new Heading($content->trim(), $level));
            },
            function (Text $part) {
                $this->next->parseBlock($part);
            }
        );
    }

}

<?php

namespace FluxBB\Markdown\Parser;

use FluxBB\Markdown\Common\Text;
use FluxBB\Markdown\Node\Heading;

class SetextHeaderParser extends AbstractParser
{

    /**
     * Parse the given block content.
     *
     * Any newly created nodes should be pushed to the stack. Any remaining content should be passed to the next parser
     * in the chain.
     *
     * @param Text $block
     * @return void
     */
    public function parseBlock(Text $block)
    {
        $block->handle(
            '{^(.+)[ \t]*\n[ \t]{0,3}(=+|-+)[ \t]*\n+}m',
            function (Text $whole, Text $content, Text $mark) {
                $level = (substr($mark, 0, 1) == '=') ? 1 : 2;

                // TODO: Parse content as inline.

                $this->stack->acceptHeading(new Heading($content->trim(), $level));
            },
            function (Text $part) {
                $this->next->parseBlock($part);
            }
        );
    }

}

Fix leading spaces in setext headers.

Fix leading spaces in setext headers.


<?php
declare(strict_types=1);

namespace ApiClients\Client\Travis\Resource\Async;

use ApiClients\Foundation\Hydrator\CommandBus\Command\HydrateCommand;
use ApiClients\Foundation\Transport\CommandBus\Command\SimpleRequestCommand;
use React\Promise\PromiseInterface;
use ApiClients\Client\Travis\Resource\Annotation as BaseAnnotation;
use function React\Promise\reject;
use function React\Promise\resolve;

class Annotation extends BaseAnnotation
{
    /**
     * @return PromiseInterface
     */
    public function refresh() : PromiseInterface
    {
        return $this->handleCommand(
            new SimpleRequestCommand('jobs/' . $this->jobId() . '/annotations')
        )->then(function ($json) {
            foreach ($json['annotations'] as $annotation) {
                if ($annotation['id'] != $this->id()) {
                    continue;
                }

                return resolve($this->handleCommand(new HydrateCommand('Annotation', $annotation)));
            }

            return reject();
        });
    }
}

<?php
declare(strict_types=1);

namespace ApiClients\Client\Travis\Resource\Async;

use ApiClients\Client\Travis\CommandBus\Command\AnnotationsCommand;
use ApiClients\Client\Travis\Resource\Annotation as BaseAnnotation;
use ApiClients\Client\Travis\Resource\AnnotationInterface;
use React\Promise\PromiseInterface;
use Rx\React\Promise;
use function ApiClients\Tools\Rx\unwrapObservableFromPromise;
use function React\Promise\reject;
use function React\Promise\resolve;

class Annotation extends BaseAnnotation
{
    /**
     * @return PromiseInterface
     */
    public function refresh() : PromiseInterface
    {
        return Promise::fromObservable(unwrapObservableFromPromise($this->handleCommand(
            new AnnotationsCommand($this->jobId())
        ))->filter(function (AnnotationInterface $annotation) {
            return $this->id() === $annotation->id();
        }));
    }
}

Refresh annotation using annotations command


<?php

namespace Orbt\StyleMirror\Css;

use Orbt\StyleMirror\Resource\SingleUseQueue;
use Orbt\ResourceMirror\Resource\GenericResource;

/**
 * Scans a stylesheet for resources.
 */
class ResourceScanner
{
    /**
     * Scanner queue.
     * @var SingleUseQueue
     */
    protected $queue;

    public function __construct(SingleUseQueue $queue)
    {
        $this->queue = $queue;
    }

    /**
     * Returns the queue used by this scanner.
     */
    public function getQueue()
    {
        return $this->queue;
    }

    /**
     * Scans CSS content for resources.
     *
     * @param GenericResource $resource
     * @param string $content
     */
    public function scan(GenericResource $resource, $content)
    {
        // Match all URL references.
        preg_match_all('!url\(\s*[\'"]?([^\'"):/]+(?:/[^\'"):/]+)*)[\'"]?\s*\)!i', $content, $matches);
        foreach ($matches[1] as $path) {
            try {
                $this->queue->add(new GenericResource($resource->resolvePath($path)));
            }
            catch (\InvalidArgumentException $e) {
                // Ignore unrecognized paths.
            }
        }
    }
}

<?php

namespace Orbt\StyleMirror\Css;

use Orbt\StyleMirror\Resource\SingleUseQueue;
use Orbt\ResourceMirror\Resource\GenericResource;

/**
 * Scans a stylesheet for resources.
 */
class ResourceScanner
{
    /**
     * Regular expression pattern for matching relative paths referenced in CSS.
     */
    const PATH_PATTERN = '!url\(\s*[\'"]?([^\'"):/]+(?:/[^\'"):/]+)*)[\'"]?\s*\)!i';

    /**
     * Scanner queue.
     * @var SingleUseQueue
     */
    protected $queue;

    public function __construct(SingleUseQueue $queue)
    {
        $this->queue = $queue;
    }

    /**
     * Returns the queue used by this scanner.
     */
    public function getQueue()
    {
        return $this->queue;
    }

    /**
     * Scans CSS content for resources.
     *
     * @param GenericResource $resource
     * @param string $content
     */
    public function scan(GenericResource $resource, $content)
    {
        // Match all URL references.
        preg_match_all(self::PATH_PATTERN, $content, $matches);
        foreach ($matches[1] as $path) {
            try {
                $this->queue->add(new GenericResource($resource->resolvePath($path)));
            }
            catch (\InvalidArgumentException $e) {
                // Ignore unrecognized paths.
            }
        }
    }
}

Move path matching pattern to a constant.


<?php $this->view('partials/head'); ?>

	<?php foreach($dashboard_layout AS $row):?>

		<?php foreach($row as $item => $data):?>

		<?php $widget->view($this, $item, $data); ?>

		<?php endforeach?>

	<?php endforeach?>

<?php $this->view('partials/foot'); ?>

<?php $this->view('partials/head'); ?>

	<?php foreach($dashboard_layout AS $row):?>

		<?php foreach($row as $item => $data):?>

			<?php if(array_key_exists('widget', $data)):?>

				<?php $widget->view($this, $data['widget'], $data); ?>

			<?php else:?>

				<?php $widget->view($this, $item, $data); ?>

			<?php endif?>

		<?php endforeach?>

	<?php endforeach?>

<?php $this->view('partials/foot'); ?>

Enable multiple widgets Override widget name by specifying widget: name in the widget variables


<?php

class mime_types {
  private static $mime_path;
  private static $mime_types = null;
  static function init(){
    self::$mime_path = $_SERVER['mime_types_path'];
    if(!self::$mime_path) self::$mime_path = "/etc/httpd/conf/mime.types";
    if(!is_file(self::$mime_path))
        throw new Exception("mime_type, invalid configuration, chk env mime_types_path");
  }

  private static function build_cache(){
    self::$mime_types = array();
    foreach(file(self::$mime_path) as $line) {
        $c = strpos($line, "#");
        if($c!==false) $line = substr($line, 0, $c);
        $line = trim($line);
        if(!$line)continue;
        $line = preg_split("#\s+#", $line);
        if(count($line)==1)continue;
        $content_type = array_shift($line);
        foreach($line as $ext)
            self::$mime_types[$ext] = $content_type;
    }
  }

  static function get_content_type($ext){
    if(!is_null(self::$mime_types))
        return self::$mime_types[$ext];

    self::build_cache();
    return self::$mime_types[$ext];
  }
}

<?php

class mime_types {
  private static $mime_path;
  private static $mime_types = null;
  static function init(){
    self::$mime_path = $_SERVER['mime_types_path'];
    if(!self::$mime_path) self::$mime_path = "/etc/httpd/conf/mime.types";
    if(!is_file(self::$mime_path))
        throw new Exception("mime_type, invalid configuration, chk env mime_types_path");
  }

  private static function build_cache(){
    self::$mime_types = array();
    foreach(file(self::$mime_path) as $line) {
        $c = strpos($line, "#");
        if($c!==false) $line = substr($line, 0, $c);
        $line = trim($line);
        if(!$line)continue;
        $line = preg_split("#\s+#", $line);
        if(count($line)==1)continue;
        $content_type = array_shift($line);
        foreach($line as $ext)
            self::$mime_types[$ext] = $content_type;
    }
  }

  static function get_ext($content_type){
    if(is_null(self::$mime_types))
      self::build_cache();

    $tmp = array_flip(self::$mime_types);

    return $tmp[$content_type];
  }

  static function get_content_type($ext){
    if(!is_null(self::$mime_types))
        return self::$mime_types[$ext];

    self::build_cache();
    return self::$mime_types[$ext];
  }
}

Add fonction for retrieve ext from contenttype

git-svn-id: 4cd2d1688610a87757c9f4de95975a674329c79f@1682 b8ca103b-dd03-488c-9448-c80b36131af2


<?php

/*
 * This file is part of the GraphAware Neo4j Client package.
 *
 * (c) GraphAware Limited <http://graphaware.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace GraphAware\Neo4j\Client\Tests\Integration;

use GraphAware\Neo4j\Client\ClientBuilder;

class IntegrationTestCase extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \GraphAware\Neo4j\Client\Client
     */
    protected $client;

    public function setUp()
    {
        $this->client = ClientBuilder::create()
            ->addConnection('http', 'http://localhost:7474')
            ->addConnection('bolt', 'bolt://localhost')
            ->build();
    }

    /**
     * Empties the graph database.
     *
     * @void
     */
    public function emptyDb()
    {
        $this->client->run('MATCH (n) OPTIONAL MATCH (n)-[r]-() DELETE r,n', null, null);
    }
}

<?php

/*
 * This file is part of the GraphAware Neo4j Client package.
 *
 * (c) GraphAware Limited <http://graphaware.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace GraphAware\Neo4j\Client\Tests\Integration;

use GraphAware\Neo4j\Client\ClientBuilder;

class IntegrationTestCase extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \GraphAware\Neo4j\Client\Client
     */
    protected $client;

    public function setUp()
    {
        $httpUri = 'http://localhost:7474';
        if (isset($_ENV['NEO4J_USER'])) {
            $httpUri = sprintf(
                '%s://%s:%s@%s:%s',
                getenv('NEO4J_SCHEMA'),
                getenv('NEO4J_USER'),
                getenv('NEO4J_PASSWORD'),
                getenv('NEO4J_HOST'),
                getenv('NEO4J_PORT')
            );
        }

        $boltUrl = 'bolt://localhost';
        if (isset($_ENV['NEO4J_USER'])) {
            $boltUrl = sprintf(
                'bolt://%s:%s@%',
                getenv('NEO4J_USER'),
                getenv('NEO4J_PASSWORD'),
                getenv('NEO4J_HOST')
            );
        }

        $this->client = ClientBuilder::create()
            ->addConnection('http', $httpUri)
            ->addConnection('bolt', $boltUrl)
            ->build();
    }

    /**
     * Empties the graph database.
     *
     * @void
     */
    public function emptyDb()
    {
        $this->client->run('MATCH (n) OPTIONAL MATCH (n)-[r]-() DELETE r,n', null, null);
    }
}

Allow to specify neo4j credentials in phpunit.xml


<?php

if (isset($_GET['l']) && ($l = $_GET['l']) && file_exist('landingPeaceLabs_'.$l.'.html'))
{

	include('landingPeaceLabs_'.$l.'.html');

}
else
{

        include('landingPeaceLabs.html');

}

<?php

if (isset($_GET['en']) && file_exist('landingPeaceLabs_en.html'))
{

	include('landingPeaceLabs_en.html');

}
else
{

        include('landingPeaceLabs.html');

}

Enable landing localized versions (2)

Enable landing localized versions (2)


<?php

$payload = json_decode(file_get_contents('php://input'));

if ($payload) {
  file_put_contents('/var/www/controversial.io/webhook-test.json', file_get_contents('php://input'));
  shell_exec('cd /var/www/controversial.io');
  shell_exec('git pull');
  shell_exec('npm install');
  shell_exec('gulp build');
  echo('done');
}

?>

<?php

$payload = json_decode(file_get_contents('php://input'));

if ($payload) {
  echo(shell_exec('cd /var/www/controversial.io 2>&1'));
  echo(shell_exec('git pull 2>&1'));
  echo(shell_exec('npm install 2>&1'));
  echo(shell_exec('gulp build 2>&1'));
  echo('done');
}

?>

Use 2>&1 for enhanced debugging

Use 2>&1 for enhanced debugging


<?php
namespace Fsv\TypographyBundle\Tests\Form\Extension;

use Fsv\TypographyBundle\Form\Extension\TextareaTypeExtension;
use Fsv\TypographyBundle\Typograph\MdashTypograph;
use Symfony\Component\Form\PreloadedExtension;
use Symfony\Component\Form\Test\TypeTestCase;

class TextareaTypeExtensionTest extends TypeTestCase
{
    public function testSubmitWithTypography()
    {
        $form = $this->factory->create('textarea', null, array(
            'typography' => true
        ));
        $form->submit('Типограф - это здорово!');

        $this->assertEquals('Типограф — это здорово!', $form->getData());
    }

    public function testSubmitWithoutTypography()
    {
        $form = $this->factory->create('textarea');
        $form->submit('Типограф - это здорово!');

        $this->assertEquals('Типограф - это здорово!', $form->getData());
    }

    protected function getExtensions()
    {
        return array(
            new PreloadedExtension(
                array(),
                array(
                    'textarea' => array(
                        new TextareaTypeExtension(new MdashTypograph(array('Text.paragraphs' => 'off')))
                    )
                )
            )
        );
    }
}

<?php
namespace Fsv\TypographyBundle\Tests\Form\Extension;

use Fsv\TypographyBundle\Form\Extension\TextareaTypeExtension;
use Symfony\Component\Form\PreloadedExtension;
use Symfony\Component\Form\Test\TypeTestCase;

class TextareaTypeExtensionTest extends TypeTestCase
{
    public function testSubmitWithTypography()
    {
        $form = $this->factory->create('textarea', null, array(
            'typography' => true
        ));
        $form->submit('Типограф - это здорово!');

        $this->assertEquals('Типограф — это здорово!', $form->getData());
    }

    public function testSubmitWithoutTypography()
    {
        $form = $this->factory->create('textarea');
        $form->submit('Типограф - это здорово!');

        $this->assertEquals('Типограф - это здорово!', $form->getData());
    }

    protected function getExtensions()
    {
        $typograph = $this->getMock('Fsv\TypographyBundle\Typograph\TypographInterface');
        $typograph
            ->expects($this->any())
            ->method('apply')
            ->with('Типограф - это здорово!')
            ->will($this->returnValue('Типограф — это здорово!'))
        ;

        return array(
            new PreloadedExtension(
                array(),
                array(
                    'textarea' => array(new TextareaTypeExtension($typograph))
                )
            )
        );
    }
}

Replace real typograph with mock

Replace real typograph with mock


<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license.
 */

declare(strict_types=1);

namespace ProxyManagerTestAsset;

/**
 * Class with a object type hint in a method - used to test iterable type hint generation
 *
 * @author Marco Pivetta <ocramius@gmail.com>
 * @license MIT
 */
class ObjectTypeHintClass
{
    /**
     * @param object $parameter
     *
     * @return object
     */
    public function iterableTypeHintMethod(object $parameter)
    {
        return $parameter;
    }
}

<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license.
 */

declare(strict_types=1);

namespace ProxyManagerTestAsset;

/**
 * Class with a object type hint in a method - used to test iterable type hint generation
 *
 * @author Marco Pivetta <ocramius@gmail.com>
 * @license MIT
 */
class ObjectTypeHintClass
{
    /**
     * @param object $parameter
     *
     * @return object
     */
    public function objectTypeHintMethod(object $parameter)
    {
        return $parameter;
    }
}

Test asset method name correction - method name was mismatching the purpose (using an `object` hint)


<?php

require __DIR__ . '/../vendor/autoload.php';

// TODO: If settings.php file does not exists throw an exception and warn users
require __DIR__ . '/../settings.php';
$app = new \Slim\App($settings);

// Register dependencies
// TODO: If dependencies.php file does not exists throw an exception and warn users
require __DIR__ . '/../dependencies.php';

// Register routes
// TODO: If routes.php file does not exists throw an exception and warn users
require __DIR__ . '/../routes.php';

// Run
$app->run();

<?php

require __DIR__ . '/../vendor/autoload.php';

$settings = [];
if (file_exists(__DIR__ . '/../settings.php')) {
    require __DIR__ . '/../settings.php';
} else {
    throw new \RuntimeException('Settings file is missing.');
}
$app = new \Slim\App($settings);

// Register dependencies
if (file_exists(__DIR__ . '/../dependencies.php')) {
    require __DIR__ . '/../dependencies.php';
} else {
    throw new \RuntimeException('Dependencies file is missing.');
}

// Register routes
if (file_exists(__DIR__ . '/../routes.php')) {
    require __DIR__ . '/../routes.php';
} else {
    throw new \RuntimeException('Routes file is missing.');
}

// Run
$app->run();

Use exceptions to warn user and stop application if any runtime file is missing


<?php
namespace exussum12\CoverageChecker\DiffLineHandle;

use exussum12\CoverageChecker\DiffLineHandle;

class DiffStart extends DiffLineHandle
{

    public function handle($line)
    {
        sscanf(
            $line,
            '@@ -%d,%d +%d,%d @@',
            $oldFrom,
            $oldTo,
            $newFrom,
            $newTo
        );

        $this->diffFileState->setCurrentPosition($newFrom -1);
    }

    public function isValid($line)
    {
        return $line[0] == '@' && $line[1] == '@';
    }
}

<?php
namespace exussum12\CoverageChecker\DiffLineHandle;

use exussum12\CoverageChecker\DiffLineHandle;

class DiffStart extends DiffLineHandle
{

    public function handle($line)
    {
        $foundVariables = sscanf(
            $line,
            '@@ -%d,%d +%d,%d @@'
        );

        $newFrom = $foundVariables[2];

        $this->diffFileState->setCurrentPosition($newFrom -1);
    }

    public function isValid($line)
    {
        return $line[0] == '@' && $line[1] == '@';
    }
}

Remove some unfound/unused variable warnings


@extends('admin.layout.master')

@section('content')
    @include('admin.layout.header')

                Created at
                Name
                Phone
                Email
                Video
                Article
                Photos

            @foreach ($entries as $entry)

                {{ $entry->created_at->format('F d, Y h:ia') }}
                {{ $entry->name }}
                {{ $entry->phone }}
                {{ $entry->email }}
                {{ $entry->video }}
                {{ $entry->article['content'] }}

                    @foreach ($entry->pictures as $picture)
                        {{ $picture }}
                    @endforeach

            @endforeach

@stop

@extends('admin.layout.master')

@section('content')

                Created at
                Name
                Phone
                Email
                Video
                Article
                Photos

            @foreach ($entries as $entry)

                {{ $entry->created_at->format('F d, Y h:ia') }}
                {{ $entry->name }}
                {{ $entry->phone }}
                {{ $entry->email }}
                {{ $entry->video }}
                {{ $entry->article['content'] }}

                    @foreach ($entry->pictures as $picture)
                        {{ $picture }}
                    @endforeach

            @endforeach

@stop

Remove include header from entry view

Remove include header from entry view


<?php

namespace Tymon\JWTAuth\Providers\User;

use Illuminate\Database\Eloquent\Model;

class EloquentUserAdapter implements UserInterface
{
    /**
     * @var \Illuminate\Database\Eloquent\Model
     */
    protected $user;

    /**
     * Create a new User instance
     *
     * @param  \Illuminate\Database\Eloquent\Model $user
     */
    public function __construct(Model $user)
    {
        $this->user = $user;
    }

    /**
     * Get the user by the given key, value
     *
     * @param  mixed  $key
     * @param  mixed  $value
     * @return Illuminate\Database\Eloquent\Model
     */
    public function getBy($key, $value)
    {
        $this->user->where($key, $value)->first();
    }
}

<?php

namespace Tymon\JWTAuth\Providers\User;

use Illuminate\Database\Eloquent\Model;

class EloquentUserAdapter implements UserInterface
{
    /**
     * @var \Illuminate\Database\Eloquent\Model
     */
    protected $user;

    /**
     * Create a new User instance
     *
     * @param  \Illuminate\Database\Eloquent\Model $user
     */
    public function __construct(Model $user)
    {
        $this->user = $user;
    }

    /**
     * Get the user by the given key, value
     *
     * @param  mixed  $key
     * @param  mixed  $value
     * @return Illuminate\Database\Eloquent\Model
     */
    public function getBy($key, $value)
    {
        return $this->user->where($key, $value)->first();
    }
}

Fix user query not being returned in getBy

JWTAuth::toUser($token) was not returning a User


<?php

namespace WPMissing;

class Post {
  function __construct($id) {
    $this->_post = get_post($id);
    $this->id = (int)$this->_post->ID;
  }

  function __get($name) {
    switch ($name) {
      case 'id':
      return $this->id;
      break;

      case 'title':
      return get_the_title($this->id);
      break;

      case 'html_content':
      global $post;
      $old_post = $post;
      setup_postdata(get_post($this->_post));
      $return = get_the_content();
      $post = $old_post;
      return $return;
      break;
    }

    return null;
  }
}

<?php

namespace WPMissing;

class Post {
  function __construct($id) {
    $this->_post = get_post($id);
    $this->id = (int)$this->_post->ID;
  }

  function __get($name) {
    switch ($name) {
      case 'title':
      return get_the_title($this->id);
      break;

      case 'html_content':
      global $post;
      $old_post = $post;
      setup_postdata(get_post($this->_post));
      $return = get_the_content();
      $post = $old_post;
      return $return;
      break;
    }

    $trace = debug_backtrace();
    trigger_error(sprintf('Undefined property via __get(): %s in %s on line %s'), $name, $trace[0]['file'], $trace[0]['line'], E_USER_ERROR);
    return null;
  }
}

Raise an error in __get()

Raise an error in __get()


<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Drupal\AppConsole\Command;

use Drupal\AppConsole\Generator\Generator;

abstract class GeneratorCommand extends ContainerAwareCommand
{
    private $generator;

    // only useful for unit tests
    public function setGenerator(Generator $generator)
    {
        $this->generator = $generator;
    }

    abstract protected function createGenerator();

    protected function getGenerator()
    {
        if (null === $this->generator) {
            $this->generator = $this->createGenerator();
            $this->generator->setSkeletonDirs($this->getSkeletonDirs());
            $this->generator->setTranslator($this->translator);
        }

        $this->addMessage('application.console.messages.completed');
        return $this->generator;
    }

    protected function getSkeletonDirs()
    {
        $skeletonDirs = array();
        $skeletonDirs[] = __DIR__.'/../Resources/skeleton';
        $skeletonDirs[] = __DIR__.'/../Resources';

        return $skeletonDirs;
    }
}

<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Drupal\AppConsole\Command;

use Drupal\AppConsole\Generator\Generator;

abstract class GeneratorCommand extends ContainerAwareCommand
{
    private $generator;

    // only useful for unit tests
    public function setGenerator(Generator $generator)
    {
        $this->generator = $generator;
    }

    abstract protected function createGenerator();

    public function getGenerator()
    {
        if (null === $this->generator) {
            $this->generator = $this->createGenerator();
            $this->generator->setSkeletonDirs($this->getSkeletonDirs());
            $this->generator->setTranslator($this->translator);
        }

        $this->addMessage('application.console.messages.completed');
        return $this->generator;
    }

    protected function getSkeletonDirs()
    {
        $skeletonDirs = array();
        $skeletonDirs[] = __DIR__.'/../Resources/skeleton';
        $skeletonDirs[] = __DIR__.'/../Resources';

        return $skeletonDirs;
    }
}

Change getGenerator method protected to public


<?php

return [
    // Source filesystem
    'source'   => new League\Flysystem\Filesystem(new League\Flysystem\Adapter\Local(storage_path('files'))),
    // Cache filesystem
    'cache'    => new League\Flysystem\Filesystem(new League\Flysystem\Memory\MemoryAdapter()),
    // Image driver (gd or imagick)
    'driver'   => 'gd',
    // Response factory
    'response' => new League\Glide\Responses\LaravelResponseFactory(),
];

<?php

return [
    // Source filesystem
    'source'         => new League\Flysystem\Filesystem(new League\Flysystem\Adapter\Local(storage_path('files'))),
    // Cache filesystem
    'cache'          => new League\Flysystem\Filesystem(new League\Flysystem\Memory\MemoryAdapter()),
    // Image driver (gd or imagick)
    'driver'         => 'gd',
    // Response factory
    'response'       => new League\Glide\Responses\LaravelResponseFactory(),
    // Max image size
    'max_image_size' => 2000 * 2000,
    // Defaults (uncomment and modify if necessary)
    //'defaults'       => [
    //    'fm' => 'jpg',
    //],
];

Add an example on how to specify default parameters


<?php

/*
 * NOTICE OF LICENSE
 *
 * Part of the Rinvex Support Package.
 *
 * This source file is subject to The MIT License (MIT)
 * that is bundled with this package in the LICENSE file.
 *
 * Package: Rinvex Support Package
 * License: The MIT License (MIT)
 * Link:    https://rinvex.com
 */

declare(strict_types=1);

namespace Rinvex\Support\Http\Requests;

use Illuminate\Foundation\Http\FormRequest as BaseFormRequest;

class FormRequest extends BaseFormRequest
{
    /**
     * {@inheritdoc}
     */
    protected function getValidatorInstance()
    {
        if (method_exists($this, 'process')) {
            $this->replace($this->container->call([$this, 'process'], [$this->all()]));
        } else {
            $this->replace(array_filter_recursive(array_trim_recursive($this->all())));
        }

        return parent::getValidatorInstance();
    }
}

<?php

/*
 * NOTICE OF LICENSE
 *
 * Part of the Rinvex Support Package.
 *
 * This source file is subject to The MIT License (MIT)
 * that is bundled with this package in the LICENSE file.
 *
 * Package: Rinvex Support Package
 * License: The MIT License (MIT)
 * Link:    https://rinvex.com
 */

declare(strict_types=1);

namespace Rinvex\Support\Http\Requests;

use Illuminate\Foundation\Http\FormRequest as BaseFormRequest;

class FormRequest extends BaseFormRequest
{
    /**
     * {@inheritdoc}
     */
    protected function getValidatorInstance()
    {
        if (method_exists($this, 'process')) {
            $this->replace($this->container->call([$this, 'process'], [$this->all()]));
        }

        return parent::getValidatorInstance();
    }
}

Remove redundant functionality, replaced by default Laravel 5.4 middleware


<?php get_template_part('templates/head'); ?>
<body <?php body_class(); ?>>

  <?php get_template_part('templates/header-top-navbar'); ?>

      <?php if (roots_display_sidebar()) : ?>
        <aside class="sidebar <?php echo roots_sidebar_class(); ?>" role="complementary">
          <?php include roots_sidebar_path(); ?>

      <?php endif; ?>
        <main class="main <?php echo roots_main_class(); ?>" role="main">

            <?php include roots_template_path(); ?>

  <?php get_template_part('templates/footer'); ?>

<?php get_template_part('templates/head'); ?>
<body <?php body_class(); ?>>

  <?php get_template_part('templates/header-top-navbar'); ?>

      <main class="main <?php echo roots_main_class(); ?>" role="main">
        <?php include roots_template_path(); ?>

      <?php if (roots_display_sidebar()) : ?>
        <aside class="sidebar <?php echo roots_sidebar_class(); ?>" role="complementary">
          <?php include roots_sidebar_path(); ?>

      <?php endif; ?>

  <?php get_template_part('templates/footer'); ?>

Revert "Revert "I don't know what changed""

This reverts commit e36c6107647bed4008f46f0ae91fd747b47b29ea.


<?php

namespace BNETDocs\Libraries;

use \CarlBennett\MVC\Libraries\Common as CommonMVCLib;
use \CarlBennett\MVC\Libraries\IP;

class BlizzardChecker {

  /**
   * Block instantiation of this object.
   */
  private function __contruct() {}

  public static function checkIfBlizzard() {
    $IP    = getenv("REMOTE_ADDR");
    $CIDRs = file_get_contents(getcwd() . "/static/a/Blizzard-CIDRs.txt");
    $CIDRs = preg_replace("/^#.*?\n/sm", "", $CIDRs);
    $CIDRs = CommonMVCLib::stripLinesWith($CIDRs, "\n");
    $CIDRs = explode("\n", $CIDRs);
    return IP::checkCIDRArray($IP, $CIDRs);
  }

}

<?php

namespace BNETDocs\Libraries;

use \CarlBennett\MVC\Libraries\Common as CommonMVCLib;
use \CarlBennett\MVC\Libraries\IP;

class BlizzardChecker {

  /**
   * Block instantiation of this object.
   */
  private function __construct() {}

  public static function checkIfBlizzard() {
    $IP    = getenv("REMOTE_ADDR");
    $CIDRs = file_get_contents(getcwd() . "/static/a/Blizzard-CIDRs.txt");
    $CIDRs = preg_replace("/^#.*?\n/sm", "", $CIDRs);
    $CIDRs = CommonMVCLib::stripLinesWith($CIDRs, "\n");
    $CIDRs = explode("\n", $CIDRs);
    return IP::checkCIDRArray($IP, $CIDRs);
  }

}

Fix typo on constructor in blizzard checker class


<?php

use yii\db\Schema;
use yii\db\Migration;

class m150720_012512_create_table_account extends Migration
{
    public function up()
    {
        $this->createTable('account', [
            'id' => Schema::TYPE_PK,
            'user_id' => Schema::integer(),
            'bio' => Schema::text() . ' NOT NULL',
            'website' => Schema::string(500),
            'facebook' => Schema::string(500),
            'twitter' => Schema::string(500),
            'soundcloud' => Schema::string(500),
        ]);
    }

    public function down()
    {
        echo "m150720_012512_create_table_account cannot be reverted.\n";

        return false;
    }
}

<?php

use yii\db\Schema;
use yii\db\Migration;

class m150720_012512_create_table_account extends Migration
{
    public function up()
    {
        $this->createTable('account', [
            'id' => Schema::TYPE_PK,
            'user_id' => Schema::integer(),
            'bio' => Schema::text() . ' NOT NULL',
            'avatar_url' => Schema::string(500),
            'website' => Schema::string(500),
            'facebook' => Schema::string(500),
            'twitter' => Schema::string(500),
            'soundcloud' => Schema::string(500),
        ]);
    }

    public function down()
    {
        echo "m150720_012512_create_table_account cannot be reverted.\n";

        return false;
    }
}

Create new database column to store avatar location.


<?php /*

  Documentation

 */ ?>

  Quickstart

  The API

  Source Code

  Slack (#dev channel)

<?php /*

  Documentation

 */ ?>

  Quickstart

  The API

  Source Code

  Roadmap

  Slack (#dev channel)

Add roadmap link to Learn page

Add roadmap link to Learn page

Added under "For Development" below the Source Code link.
Road icon (http://fontawesome.io/icon/road/)

Feel free to suggest putting this somewhere else


<?php namespace ThibaudDauce\MoloquentInheritance;

use ReflectionClass;

trait MoloquentInheritanceTrait {

    public $parentClasses;

    /**
     * Boot the moloquent inheritance for a model.
     *
     * @return void
     */
    public static function bootMoloquentInheritanceTrait()
    {
        static::addGlobalScope(new MoloquentInheritanceScope);
    }

    /**
     * Fill the model with an array of attributes.
     *
     * @override Illuminate\Database\Eloquent\Model
     * @param  array  $attributes
     * @return $this
     *
     * @throws MassAssignmentException
     */
    public function fill(array $attributes)
    {
        $this->setParentClasses();

        return parent::fill($attributes);
    }

    public function getParentClasses() {

        $reflection = new ReflectionClass($this);

        $classes = [$reflection->getName()];

        while ($reflection->getName() !== get_class()) {
            $reflection = $reflection->getParentClass();
            $classes[] = $reflection->getName();
        }

        return $classes;
    }

    public function setParentClasses() {

        $this->attributes['parent_classes'] = $this->getParentClasses();
    }

    /**
     * Create a new model instance that is existing.
     *
     * @override Illuminate\Database\Eloquent\Model
     * @param  array  $attributes
     * @return \Illuminate\Database\Eloquent\Model|static
     */
    public function newFromBuilder($attributes = array())
    {
        $class = $attributes['parent_classes'][0];

        if ($this instanceof $class)
            return parent::newFromBuilder($attributes);

        $instance = new $class;

        $instance->newFromBuilder((array) $attributes);

        return $instance;
    }
}

<?php namespace ThibaudDauce\MoloquentInheritance;

use ReflectionClass;

trait MoloquentInheritanceTrait {

    public $parentClasses;

    /**
     * Boot the moloquent inheritance for a model.
     *
     * @return void
     */
    public static function bootMoloquentInheritanceTrait()
    {
        static::addGlobalScope(new MoloquentInheritanceScope);
    }

    /**
     * Fill the model with an array of attributes.
     *
     * @override Illuminate\Database\Eloquent\Model
     * @param  array  $attributes
     * @return $this
     *
     * @throws MassAssignmentException
     */
    public function fill(array $attributes)
    {
        $this->setParentClasses();

        return parent::fill($attributes);
    }

    public function getParentClasses() {

        $reflection = new ReflectionClass($this);

        $classes = [$reflection->getName()];

        while ($reflection->getName() !== get_class()) {
            $reflection = $reflection->getParentClass();
            $classes[] = $reflection->getName();
        }

        return $classes;
    }

    public function setParentClasses() {

        $this->attributes['parent_classes'] = $this->getParentClasses();
    }

    /**
     * Create a new model instance that is existing.
     *
     * @override Illuminate\Database\Eloquent\Model
     * @param  array  $attributes
     * @return \Illuminate\Database\Eloquent\Model|static
     */
    public function newFromBuilder($attributes = array())
    {
        $class = $attributes['parent_classes'][0];
        $instance = new $class;

        $instance = $instance->newInstance(array(), true);
        $instance->setRawAttributes((array) $attributes);

        return $instance;
    }
}

Fix bug with exists property

Fix bug with exists property


<?php
/**
  * Extension:Josa
  * Author: JuneHyeon Bae <devunt@gmail.com>
  * Original implementation by Park Shinjo <peremen@gmail.com>
  * License: MIT License
*/

if ( !defined( 'MEDIAWIKI' ) ) {
	die( 'This file is a MediaWiki extension, it is not a vaild entry point' );
}

$wgExtensionCredits['parserhook'][] = array(
	'path' => __FILE__,
	'name' => 'Josa',
	'author' => 'JuneHyeon Bae (devunt)',
	'url' => 'https://www.mediawiki.org/wiki/Extension:Josa',
	'descriptionmsg' => 'josa-desc',
	'version'  => '0.1.1',
);
$wgHooks['ParserFirstCallInit'][] = 'Josa::InitParserFunction';

// Load i18n files
$wgMessagesDirs['Josa'] = __DIR__ . '/i18n';
$wgExtensionMessagesFiles['JosaMagic'] = __DIR__ . '/Josa.i18n.magic.php';

$wgAutoloadClasses['Josa'] = __DIR__ . '/Josa.class.php';

<?php
/**
  * Extension:Josa
  * Author: JuneHyeon Bae <devunt@gmail.com>
  * Original implementation by Park Shinjo <peremen@gmail.com>
  * License: MIT License
*/

if ( !defined( 'MEDIAWIKI' ) ) {
	die( 'This file is a MediaWiki extension, it is not a vaild entry point' );
}

$wgExtensionCredits['parserhook'][] = array(
	'path' => __FILE__,
	'name' => 'Josa',
	'author' => 'JuneHyeon Bae (devunt)',
	'url' => 'https://www.mediawiki.org/wiki/Extension:Josa',
	'descriptionmsg' => 'josa-desc',
	'version'  => '0.1.1',
	'license-name' => 'MIT',
);
$wgHooks['ParserFirstCallInit'][] = 'Josa::InitParserFunction';

// Load i18n files
$wgMessagesDirs['Josa'] = __DIR__ . '/i18n';
$wgExtensionMessagesFiles['JosaMagic'] = __DIR__ . '/Josa.i18n.magic.php';

$wgAutoloadClasses['Josa'] = __DIR__ . '/Josa.class.php';

Add 'license-name' matching SPDX conventions

References:
http://spdx.org/licenses/
https://www.mediawiki.org/wiki/Manual:$wgExtensionCredits#license-name

Change-Id: I6f221c46d1e2746b8882ca57b040743dfb4ca0c1


<?php
    class ImageController {
        public static function create( $image ) {
            include_once 'models/image.php';
            include_once 'models/extentions.php';
            if ( !isset( $_SESSION[ 'user' ][ 'username' ] ) ) {
                throw new HTTPUnauthorizedException();
            }
            $config = getConfig();
            $name = $image[ 'name' ];
            $tmp_name = $image[ 'tmp_name' ];
            $user = User::find_by_username( $_SESSION[ 'user' ][ 'username' ] );
            $image = new Image();
            $image->tmp_name = $tmp_name;
            $image->name = $name;
            $image->user = $user;
            try {
                $image->save();
            }
            catch ( ModelValidationException $e ) {
                go( 'user', 'update', array( 'username' => $user->username, $e->error => true ) );
            }
            go( 'user', 'view', array( 'username' => $user->username ) );
        }
    }
?>

<?php
    class ImageController {
        public static function create( $image ) {
            include_once 'models/image.php';
            include_once 'models/extentions.php';
            if ( !isset( $_SESSION[ 'user' ][ 'username' ] ) ) {
                throw new HTTPUnauthorizedException();
            }
            $config = getConfig();
            global $config;
            $name = $image[ 'name' ];
            $tmp_name = $image[ 'tmp_name' ];
            $user = User::find_by_username( $_SESSION[ 'user' ][ 'username' ] );
            $image = new Image();
            $image->tmp_name = $tmp_name;
            $image->name = $name;
            $image->user = $user;
            try {
                $image->save();
            }
            catch ( ModelValidationException $e ) {
                go( 'user', 'update', array( 'username' => $user->username, $e->error => true ) );
            }
            go( 'user', 'view', array( 'username' => $user->username ) );
        }
    }
?>

Make config a global variable

Make config a global variable


<?php

namespace spec\Md\Phunkie\Cats;

use Md\Phunkie\Cats\StateT;
use function Md\Phunkie\Functions\state\put;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class StateTSpec extends ObjectBehavior
{
    function it_runs_function_under_a_context()
    {
        $increment = new StateT(Some(function($n) { return Some(Pair($n + 1, $n)); }));
        expect($increment->run(1))->toBeLike(Some(Pair(2,1)));
    }
}

<?php

namespace spec\Md\Phunkie\Cats;

use Md\Phunkie\Cats\StateT;
use function Md\Phunkie\Functions\state\put;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class StateTSpec extends ObjectBehavior
{
    function it_runs_function_under_a_context()
    {
        $this->beConstructedWith(Some(function($n) { return Some(Pair($n + 1, $n)); }));
        $this->run(1)->shouldBeLike(Some(Pair(2,1)));
    }
}

Replace expect with native matchers in StateT


<?php

namespace DNADesign\Elemental\GraphQL;

use DNADesign\Elemental\Models\ElementalArea;
use GraphQL\Type\Definition\ResolveInfo;
use SilverStripe\GraphQL\OperationResolver;

class ReadOneAreaResolver implements OperationResolver
{
    public function resolve($object, array $args, $context, ResolveInfo $info)
    {
        $area = ElementalArea::get()->byID($args['ID']);

        if (!$area->canView($context['currentUser'])) {
            throw new \Exception('Current user cannot view element areas');
        }

        return $area;
    }
}

<?php

namespace DNADesign\Elemental\GraphQL;

use DNADesign\Elemental\Models\ElementalArea;
use Exception;
use GraphQL\Type\Definition\ResolveInfo;
use InvalidArgumentException;
use SilverStripe\GraphQL\OperationResolver;

class ReadOneAreaResolver implements OperationResolver
{
    public function resolve($object, array $args, $context, ResolveInfo $info)
    {
        $area = ElementalArea::get()->byID($args['ID']);

        if (!$area) {
            throw new InvalidArgumentException('Could not find elemental area matching ID ' . $args['ID']);
        }

        if (!$area->canView($context['currentUser'])) {
            throw new Exception('Current user cannot view element areas');
        }

        return $area;
    }
}

FIX Assert elemental areas exist before calling methods on them


<?php

namespace Mo\FlashCardsBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;

class ApiController extends Controller
{
    public function cardsAction($group)
    {
        $cards = array(
            'dog' => 'doggy',
            'cat' => 'kitty'
        );

        // setup response
        $response = new JsonResponse();
        $response->setData($cards);

        return $response;
    }
}

<?php

namespace Mo\FlashCardsBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * Actions handling the data flow.
 */
class ApiController extends Controller
{
    /**
     * @param string $group
     * @return \Symfony\Component\HttpFoundation\JsonResponse
     */
    public function cardsAction($group)
    {
        $cards = array(
            'dog' => 'doggy',
            'cat' => 'kitty'
        );

        // setup response
        $response = new JsonResponse();
        $response->setData($cards);

        return $response;
    }
}

Add comments to the API controller.

Add comments to the API controller.


<?php

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

class CreateCoursePeriodTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('course_period', function (Blueprint $table) {
            $table->string('course_id');
            $table->unsignedInteger('period_id');
            $table->timestamps();

            $table->primary(['course_id', 'period_id']);
            $table->foreign('course_id')->references('id')->on('courses')
                ->onUpdate('cascade')->onDelete('cascade');
            $table->foreign('period_id')->references('id')->on('periods')
                ->onUpdate('cascade')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('course_period');
    }
}

<?php

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

class CreateCoursePeriodTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('course_period', function (Blueprint $table) {
            $table->string('course_id');
            $table->unsignedInteger('period_id');
            $table->string('location');
            $table->timestamps();

            $table->primary(['course_id', 'period_id']);
            $table->foreign('course_id')->references('id')->on('courses')
                ->onUpdate('cascade')->onDelete('cascade');
            $table->foreign('period_id')->references('id')->on('periods')
                ->onUpdate('cascade')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('course_period');
    }
}

Add location field in relation between course and period


<?php
/**
 * Lithium: the most rad php framework
 *
 * @copyright     Copyright 2009, Union of RAD (http://union-of-rad.org)
 * @license       http://opensource.org/licenses/bsd-license.php The BSD License
 */

namespace li3_bot\extensions\command\bot;

/**
 * Abstract class for Bot plugins
 *
 */
abstract class Plugin extends \lithium\console\Command {

	/**
	 * Called on each ping
	 *
	 * @return string
	 */
	abstract public function poll();

	/**
	 * Process messages and message output
	 * {{{
	 * $data = array(
	 *     'channel' => '#li3', 'nick'=> 'li3_bot'
	 *     'user' => 'gwoo', 'message' => '~cool'
	 * );
	 * }}}
	 *
	 * @param array $data
	 * @return string
	 */
	abstract public function process($data);
}
?>

<?php
/**
 * Lithium: the most rad php framework
 *
 * @copyright     Copyright 2009, Union of RAD (http://union-of-rad.org)
 * @license       http://opensource.org/licenses/bsd-license.php The BSD License
 */

namespace li3_bot\extensions\command\bot;

/**
 * Abstract class for Bot plugins
 *
 */
abstract class Plugin extends \lithium\console\Command {

	/**
	 * Called on each ping
	 *
	 * @return string
	 */
	//abstract public function poll();

	/**
	 * Process messages and message output
	 * {{{
	 * $data = array(
	 *     'channel' => '#li3', 'nick'=> 'li3_bot'
	 *     'user' => 'gwoo', 'message' => '~cool'
	 * );
	 * }}}
	 *
	 * @param array $data
	 * @return string
	 */
	//abstract public function process($data);
}
?>

Revert "Enable abstract plugin class."

Revert "Enable abstract plugin class."

This reverts commit 053396dbcf45085ed2380514f0f66e0ba2e059ab.


<?php

namespace App\Controllers;

class AuthController
{
    public function login()
    {
        var_dump(input());
        return $input;
    }

    public function register()
    {
        $inputs = input()->all(['email', 'password']);

        if (!$this->isValid($inputs))
        {
            return 'form is not valid';
        }

        if ($this->isEmailExist($inputs['email']))
        {
            return 'email already used';
        }

        \Builder::table('users')->insert([
            'email' => $inputs['email'],
            'password' => sha1($inputs['email']),
            'role' => 'student'
        ]);

        return 'success';
    }

    private function isEmailExist($email)
    {
        return !is_null(\Builder::table('users')->where('email', '=', $email)->first());
    }

    /**
     * Check if array has falsy values
     *
     * @param arrays $inputs
     * @return boolean
     */
    private function isValid($inputs)
    {
        return !in_array(false, $this->isEmpty($inputs));
    }

    /**
     * Transform all values in array to (boolean) false depending
     * on whether its empty or not. The element will be false if
     * it is empty.
     *
     * @param array $arrays
     * @return array
     */
    private function isEmpty($arrays)
    {
        return array_map(
            function ($value)
            {
                return !empty($value);
            },
            $arrays
        );
    }
}

<?php

namespace App\Controllers;

class AuthController
{
    public function login()
    {
        var_dump(input());
        return $input;
    }

    public function register()
    {
        $inputs = input()->all(['email', 'password']);

        if (!$this->isValid($inputs))
        {
            return 'form is not valid';
        }

        if ($this->isEmailExist($inputs['email']))
        {
            return 'email already used';
        }

        \Builder::table('users')->insert([
            'email' => $inputs['email'],
            'password' => password_hash($inputs['password'], PASSWORD_DEFAULT),
            'role' => 'student'
        ]);

        return 'success';
    }

    private function isEmailExist($email)
    {
        return !is_null(\Builder::table('users')->where('email', '=', $email)->first());
    }

    /**
     * Check if array has falsy values
     *
     * @param array $inputs
     * @return boolean
     */
    private function isValid($inputs)
    {
        return !in_array(false, $this->isEmpty($inputs));
    }

    /**
     * Transform all values in array to (boolean) false depending
     * on whether its empty or not. The element will be false if
     * it is empty.
     *
     * @param array $arrays
     * @return array
     */
    private function isEmpty($arrays)
    {
        return array_map(
            function ($value)
            {
                return !empty($value);
            },
            $arrays
        );
    }
}

Improve password hashing store in registration


<?php
/**
 * Application Settings
 * @author John Kloor <kloor@bgsu.edu>
 * @copyright 2017 Bowling Green State University Libraries
 * @license MIT
 */

use Symfony\Component\Yaml\Yaml;

// Setup the default settings for the application.
$settings = [
    // Application settings.
    'app' => [
        // Whether to enable debug information.
        'debug' => false,

        // Path to log file, if any.
        'log' => false
    ],

    // Template settings.
    'template' => [
        // Path to search for templates before this package's templates.
        'path' => false,

        // Filename of template that defines a page. Default: page.html.twig
        'page' => false
    ],

    // SMTP settings.
    'smtp' => [
        // Server hostname.
        'host' => false,

        // Server port number. Default: 25
        'port' => 25
    ],

    // URI index requests are redirected to.
    'redirect' => false,

    // Actions handled by the application.
    'actions' => []
];

// Check if a config.yaml file exists.
$file = dirname(__DIR__) . '/config.yaml';

if (file_exists($file)) {
    // If so, load the settings from that file.
    $settings = array_replace_recursive(
        $settings,
        Yaml::parse(file_get_contents($file))
    );
}

// Return the complete settings array.
return $settings;

<?php
/**
 * Application Settings
 * @author John Kloor <kloor@bgsu.edu>
 * @copyright 2017 Bowling Green State University Libraries
 * @license MIT
 */

use Symfony\Component\Yaml\Yaml;

// Setup the default settings for the application.
$settings = [
    // Application settings.
    'app' => [
        // Whether to enable debug information.
        'debug' => false,

        // Path to log file, if any.
        'log' => false,

        // URI index requests are redirected to.
        'redirect' => false
    ],

    // Template settings.
    'template' => [
        // Path to search for templates before this package's templates.
        'path' => false,

        // Filename of template that defines a page. Default: page.html.twig
        'page' => false
    ],

    // SMTP settings.
    'smtp' => [
        // Server hostname.
        'host' => false,

        // Server port number. Default: 25
        'port' => 25
    ],

    // Actions handled by the application.
    'actions' => []
];

// Check if a config.yaml file exists.
$file = dirname(__DIR__) . '/config.yaml';

if (file_exists($file)) {
    // If so, load the settings from that file.
    $settings = array_replace_recursive(
        $settings,
        Yaml::parse(file_get_contents($file))
    );
}

// Return the complete settings array.
return $settings;

Move redirect setting to correct location.


Who to follow

    @if (count($follow_suggestions))
        @foreach ($follow_suggestions as $follow_suggestion)

                username) }}">
                    photo($follow_suggestion->id) }}" style="max-width: 48px; max-height: 48px;" alt="User photo">

                        username) }}" style="color: #555;">
                            {{ $follow_suggestion->name }}

                        @if ($follow_suggestion->verified > 0)

                        @endif
                        {{ '@' . $follow_suggestion->username }}

                    <user-follow :original-following="false" :user-id="{{ $follow_suggestion->id }}" :current-user-id="{{ Auth::id() }}"></user-follow>

        @endforeach
        Search by interests
    @else
        No suggestions.
    @endif

Who to follow

    @if (count($follow_suggestions))
        @foreach ($follow_suggestions as $follow_suggestion)

                username) }}">
                    photo($follow_suggestion->id) }}" style="max-width: 32px; max-height: 32px;" alt="User photo">

                        username) }}" style="color: #555;">
                            {{ $follow_suggestion->name }}

                        @if ($follow_suggestion->verified > 0)

                        @endif
                        username }}">{{ '@' . $follow_suggestion->username }}

                    <user-follow :original-following="false" :user-id="{{ $follow_suggestion->id }}" :current-user-id="{{ Auth::id() }}"></user-follow>

        @endforeach
        Search by interests
    @else
        No suggestions.
    @endif

Reduce who to follow image size

Reduce who to follow image size


<?php

namespace App\Sharp\Commands;

use Code16\Sharp\EntityList\Commands\EntityCommand;
use Code16\Sharp\EntityList\EntityListQueryParams;

class SpaceshipSynchronize extends EntityCommand
{

    /**
     * @return string
     */
    public function label(): string
    {
        return "Synchronize the gamma-spectrum";
    }

    /**
     * @param EntityListQueryParams $params
     * @param array $data
     * @return array
     */
    public function execute(EntityListQueryParams $params, array $data=[]): array
    {
        return $this->info("Gamma spectrum synchronized!");
    }

    public function confirmationText()
    {
        return "Sure, really?";
    }

    public function authorize():bool
    {
        return sharp_user()->hasGroup("boss");
    }
}

<?php

namespace App\Sharp\Commands;

use Code16\Sharp\EntityList\Commands\EntityCommand;
use Code16\Sharp\EntityList\EntityListQueryParams;

class SpaceshipSynchronize extends EntityCommand
{

    /**
     * @return string
     */
    public function label(): string
    {
        return "Synchronize the gamma-spectrum";
    }

    /**
     * @param EntityListQueryParams $params
     * @param array $data
     * @return array
     */
    public function execute(EntityListQueryParams $params, array $data=[]): array
    {
        sleep(2);
        return $this->info("Gamma spectrum synchronized!");
    }

    public function confirmationText()
    {
        return "Sure, really?";
    }

    public function authorize():bool
    {
        return sharp_user()->hasGroup("boss");
    }
}

[saturn] Increase time for gamma spectrum command


<?php

namespace common\models\comments;

use yii\base\Exception;

class NestedSetComment extends Comment
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%comment_ns}}';
    }

    public static function findByPostInternal($postId)
    {
        throw new Exception('Method is not implemented');
    }
}

<?php

namespace common\models\comments;

use yii\db\Query;

class NestedSetComment extends Comment
{
    public $parent_id;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%comment_ns}}';
    }

    public static function findByPostInternal($postId)
    {
        return [];
    }

    public function beforeSave($insert)
    {
        if (!parent::beforeSave($insert)) {
            return false;
        }

        $query = new Query();
        $query
            ->select('COUNT(*)')
            ->where(['post_id' => $this->post_id])
            ->from(static::tableName());
        $count = $query->scalar($this->getDb());

        if ($count == 0) {
            $this->left = 1;
            $this->right = 2;
            $this->level = 1;
        } else {
            if (empty($this->parent_id)) {
                $query = new Query();
                $query
                    ->select('MAX({{right}})')
                    ->where(['post_id' => $this->post_id])
                    ->from(static::tableName());
                $maxRight = $query->scalar($this->getDb());

                $this->left = $maxRight + 1;
                $this->right = $maxRight + 2;
                $this->level = 1;
            } else {

            }
        }

        return true;
    }
}

Implement addition of the root nodes of the Nested Set.


<?php
/**
 * Garp_Model_Db_Snippet
 * Snippet model. Snippets are small dynamic chunks of content.
 *
 * @package Garp_Model_Db
 * @author  Harmen Janssen <harmen@grrr.nl>
 */
class Garp_Model_Db_Snippet extends Model_Base_Snippet {
    /**
     * Fetch a snippet by its identifier
     *
     * @param string $identifier
     * @return Garp_Db_Table_Row
     */
    public function fetchByIdentifier($identifier) {
        if (!$identifier) {
            throw new InvalidArgumentException('Snippet identifier is required');
        }
        $select = $this->select()->where('identifier = ?', $identifier);
        if ($result = $this->fetchRow($select)) {
            return $result;
        }
        throw new Exception('Snippet not found: ' . $identifier);
    }

    /**
     * BeforeFetch: filters out snippets where is_editable = 0 in the CMs.
     *
     * @param array $args
     * @return void
     */
    public function beforeFetch(&$args) {
        $model = &$args[0];
        $select = &$args[1];
        if (!$model->isCmsContext()) {
            return;
        }
        // Sanity check: this project might be spawned without the is_editable column,
        // it was added to Snippet at May 1 2013.
        if ($this->getFieldConfiguration('is_editable')) {
            $select->where('is_editable = ?', 1);
        }
    }
}

<?php
/**
 * Garp_Model_Db_Snippet
 * Snippet model. Snippets are small dynamic chunks of content.
 *
 * @package Garp_Model_Db
 * @author  Harmen Janssen <harmen@grrr.nl>
 */
class Garp_Model_Db_Snippet extends Model_Base_Snippet {
    /**
     * Fetch a snippet by its identifier
     *
     * @param string $identifier
     * @return Garp_Db_Table_Row
     */
    public function fetchByIdentifier($identifier) {
        if (!$identifier) {
            throw new InvalidArgumentException('Snippet identifier is required');
        }
        $select = $this->select()->where('identifier = ?', $identifier);
        if ($result = $this->fetchRow($select)) {
            return $result;
        }
        if (!Zend_Registry::get('config')->snippets->ignoreMissing) {
            throw new Exception('Snippet not found: ' . $identifier);
        }
        // Return fallback row, where text is set to $identifier, in order to provide some fallback.
        return $this->createRow([
            'has_text' => 1,
            'text' => $identifier,
        ]);
    }

    /**
     * BeforeFetch: filters out snippets where is_editable = 0 in the CMs.
     *
     * @param array $args
     * @return void
     */
    public function beforeFetch(&$args) {
        $model = &$args[0];
        $select = &$args[1];
        if (!$model->isCmsContext()) {
            return;
        }
        // Sanity check: this project might be spawned without the is_editable column,
        // it was added to Snippet at May 1 2013.
        if ($this->getFieldConfiguration('is_editable')) {
            $select->where('is_editable = ?', 1);
        }
    }
}

Allow the "crash early" behavior of snippets to be configured

This way it can be turned off in testing environment, making testing
setup simpler.


<?php

/**
 *
 *
 * @author <marcus@silverstripe.com.au>
 * @license BSD License http://www.silverstripe.org/bsd-license
 */
class PageControllerThemeExtension extends Extension {
	public function onAfterInit() {
		Requirements::block(THIRDPARTY_DIR .'/jquery/jquery.js');
		Requirements::javascript('frontend-dashboards/javascript/jquery-1.10.2.min.js');
		Requirements::javascript(THIRDPARTY_DIR . '/jquery-cookie/jquery.cookie.js');
		Requirements::javascript(THIRDPARTY_DIR . '/jquery-ui/jquery-ui.js');
		//Requirements::javascript('frontend-dashboards/javascript/jquery-migrate-1.2.1.min.js');
		Requirements::javascript(THIRDPARTY_DIR . '/jquery-entwine/dist/jquery.entwine-dist.js');
		Requirements::block('frontend-dashboards/javascript/dashboards.js');
		Requirements::javascript('themes/ssau-minimalist/js/modernizr.js');
		Requirements::javascript('themes/ssau-minimalist/js/foundation.min.js');
	}
}

<?php

/**
 *
 *
 * @author <marcus@silverstripe.com.au>
 * @license BSD License http://www.silverstripe.org/bsd-license
 */
class PageControllerThemeExtension extends Extension {
	public function onAfterInit() {
		if (Config::inst()->get('SSViewer', 'theme') == 'ssau-minimalist') {
			Requirements::block(THIRDPARTY_DIR .'/jquery/jquery.js');
			Requirements::javascript('frontend-dashboards/javascript/jquery-1.10.2.min.js');
			Requirements::javascript(THIRDPARTY_DIR . '/jquery-cookie/jquery.cookie.js');
			Requirements::javascript(THIRDPARTY_DIR . '/jquery-ui/jquery-ui.js');
			//Requirements::javascript('frontend-dashboards/javascript/jquery-migrate-1.2.1.min.js');
			Requirements::javascript(THIRDPARTY_DIR . '/jquery-entwine/dist/jquery.entwine-dist.js');
			Requirements::block('frontend-dashboards/javascript/dashboards.js');
			Requirements::javascript('themes/ssau-minimalist/js/modernizr.js');
			Requirements::javascript('themes/ssau-minimalist/js/foundation.min.js');
		}
	}
}

FIX Only apply theme settings if theme == ssau-minimalist


<?php

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

namespace Aes3xs\Yodler\Tests\Connection;

use Aes3xs\Yodler\Connection\Connection;
use Aes3xs\Yodler\Connection\Server;
use Aes3xs\Yodler\Connection\User;
use Aes3xs\Yodler\Variable\VariableList;

class ConnectionTest extends \PHPUnit_Framework_TestCase
{
    public function testConstruct()
    {
        $server = new Server(null, null);
        $user = new User(null);
        $variables = new VariableList();
        $connection = new Connection('test', $server, $user, $variables);

        $this->assertEquals('test', $connection->getName());
        $this->assertSame($server, $connection->getServer());
        $this->assertSame($user, $connection->getUser());
        $this->assertSame($variables, $connection->getVariables());
    }
}

<?php

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

namespace Aes3xs\Yodler\Tests\Connection;

use Aes3xs\Yodler\Connection\Connection;
use Aes3xs\Yodler\Connection\ServerInterface;
use Aes3xs\Yodler\Connection\UserInterface;
use Aes3xs\Yodler\Variable\VariableListInterface;

class ConnectionTest extends \PHPUnit_Framework_TestCase
{
    public function testConstruct()
    {
        $serverMock = $this->createMock(ServerInterface::class);
        $userMock = $this->createMock(UserInterface::class);
        $variablesMock = $this->createMock(VariableListInterface::class);
        $connection = new Connection('test', $serverMock, $userMock, $variablesMock);

        $this->assertEquals('test', $connection->getName());
        $this->assertSame($serverMock, $connection->getServer());
        $this->assertSame($userMock, $connection->getUser());
        $this->assertSame($variablesMock, $connection->getVariables());
    }
}

Rewrite Connection test to use mocking

Rewrite Connection test to use mocking


<!DOCTYPE html>

        <title>Laravel</title>

        <link href="//fonts.googleapis.com/css?family=Lato:300" rel="stylesheet" type="text/css">

            @if ($username)
                Logout {{ $username }}
            @else
                {{ trans("public.links.login") }} |
                {{ trans("public.links.register") }}
            @endif

 {{ trans("public.words.welcome") }}

@extends('layouts.master')

@section('content')

 {{ trans("public.words.welcome") }}

@endsection

Convert existing home page to use master template


<?php namespace Aranw\ETagsMiddleware;

use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;

class ETags implements HttpKernelInterface {

    /**
     * The wrapped kernel implementation.
     *
     * @var \Symfony\Component\HttpKernel\HttpKernelInterface
     */
    protected $app;

    /**
     * Create a new RateLimiter instance.
     *
     * @param  \Symfony\Component\HttpKernel\HttpKernelInterface  $app
     * @return void
     */
    public function __construct(HttpKernelInterface $app)
    {
        $this->app = $app;
    }

    /**
     * Handle the given request and get the response.
     *
     * @implements HttpKernelInterface::handle
     *
     * @param  \Symfony\Component\HttpFoundation\Request  $request
     * @param  int   $type
     * @param  bool  $catch
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function handle(SymfonyRequest $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
    {
        // Handle on passed down request
        $response = $this->app->handle($request, $type, $catch);

        if ( ! $response->headers->has('etag')) {
            $responseETag = md5($response->getContent());
            $response->setEtag($responseETag);
        }

        if ($response->isNotModified($request)) {
            $response->setNotModified();
            return $response; // Return our empty 304 not modified response
            // Return 304 if ETag matches given response
        }

        return $response;
    }
}

<?php namespace Aranw\ETagsMiddleware;

use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;

class ETags implements HttpKernelInterface {

    /**
     * The wrapped kernel implementation.
     *
     * @var \Symfony\Component\HttpKernel\HttpKernelInterface
     */
    protected $app;

    /**
     * Create a new RateLimiter instance.
     *
     * @param  \Symfony\Component\HttpKernel\HttpKernelInterface  $app
     * @return void
     */
    public function __construct(HttpKernelInterface $app)
    {
        $this->app = $app;
    }

    /**
     * Handle the given request and get the response.
     *
     * @implements HttpKernelInterface::handle
     *
     * @param  \Symfony\Component\HttpFoundation\Request  $request
     * @param  int   $type
     * @param  bool  $catch
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function handle(SymfonyRequest $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
    {
        // Handle on passed down request
        $response = $this->app->handle($request, $type, $catch);

        if ( ! $response->headers->has('etag')) {
            $responseETag = md5($response->getContent());
            $response->setEtag($responseETag);
        }

        if ($response->isNotModified($request)) {
            return $response; // Return our empty 304 not modified response
            // Return 304 if ETag matches given response
        }

        return $response;
    }
}

Remove the extra setNotModified function call.

Signed-off-by: Hunter Skrasek <6e2f9e6111e77edd0c446ea7a84e25323d137a61@perk.com>


<?php

namespace ProcessWire\GraphQL\Field\Page;

use Youshido\GraphQL\Field\AbstractField;
use Youshido\GraphQL\Execution\ResolveInfo;
use Youshido\GraphQL\Type\NonNullType;
use ProcessWire\GraphQL\Type\Object\PageArrayType as PageArrayObjectType;

class PageParentsField extends AbstractField {

  public function getType()
  {
    return new NonNullType(new PageArrayObjectType());
  }

  public function getName()
  {
    return 'parents';
  }

  public function getDescription()
  {
    return "Return this page's parent pages as PageArray.";
  }

  public function resolve($value, array $args, ResolveInfo $info)
  {
    return $value->parents;
  }

}

<?php

namespace ProcessWire\GraphQL\Field\Page;

use Youshido\GraphQL\Field\AbstractField;
use Youshido\GraphQL\Execution\ResolveInfo;
use Youshido\GraphQL\Type\NonNullType;
use Youshido\GraphQL\Field\InputField;
use Youshido\GraphQL\Config\Field\FieldConfig;
use ProcessWire\GraphQL\Type\Scalar\SelectorType;
use ProcessWire\GraphQL\Type\Object\PageArrayType as PageArrayObjectType;

class PageParentsField extends AbstractField {

  public function getType()
  {
    return new NonNullType(new PageArrayObjectType());
  }

  public function getName()
  {
    return 'parents';
  }

  public function getDescription()
  {
    return "Return this page's parent pages as PageArray. Optionally filtered by a selector.";
  }

  public function build(FieldConfig $config)
  {
    $config->addArgument(new InputField([
      'name' => SelectorType::ARGUMENT_NAME,
      'type' => new SelectorType(),
    ]));
  }

  public function resolve($value, array $args, ResolveInfo $info)
  {
    $s = SelectorType::ARGUMENT_NAME;
    if (isset($args[$s])) return $value->parents($args[$s]);
    return $value->parents;
  }

}

Add optional selector argument support.

Add optional selector argument support.


<?php namespace TecBeast\PreLaunch\Middleware;

use Closure;

class AppIsInPrelaunch {

	/**
	 * Redirects the user to the prelaunch route if the Enviroment
	 * APP_PRELAUNCH is set to true
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	public function handle($request, Closure $next)
	{
		if(env('APP_PRELAUNCH',false) AND !\Request::is('prelaunch*')) {
			return redirect()->route('prelaunch');
		}

		return $next($request);
	}

}

<?php namespace TecBeast\PreLaunch\Middleware;

use Closure;

class AppIsInPrelaunch {

	/**
	 * Redirects the user to the prelaunch route if the Enviroment
	 * APP_PRELAUNCH is set to true
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @return mixed
	 */
	public function handle($request, Closure $next)
	{
		if(env('APP_PRELAUNCH',false) AND !\Request::is('prelaunch*')) {
			return redirect()->url('prelaunch');
		}

		return $next($request);
	}

}

[Fix] Set the middleware to redirect to an url instead of the removed route


<?php
namespace Payum\Core;

interface GatewayInterface
{
    /**
     * @param mixed   $request
     * @param boolean $catchReply
     *
     * @throws \Payum\Core\Exception\RequestNotSupportedException if there is not an action which able to process the request.
     * @throws \Payum\Core\Reply\ReplyInterface                   when a gateway needs some external tasks to be executed. like a redirect to a gateway site or a page with credit card form. if $catchReply set to false the reply will be returned.
     *
     * @return \Payum\Core\Reply\ReplyInterface|null
     */
    public function execute($request, $catchReply = false);
}

<?php
namespace Payum\Core;

interface GatewayInterface
{
    /**
     * @param mixed   $request
     * @param boolean $catchReply If false the reply behave like an exception. If true the reply will be caught internally and returned.
     *
     * @throws \Payum\Core\Exception\RequestNotSupportedException If there is not an action which able to process the request.
     * @throws \Payum\Core\Reply\ReplyInterface                   Gateway throws reply if some external tasks have to be done. For example show a credit card form, an iframe or perform a redirect.
     *
     * @return \Payum\Core\Reply\ReplyInterface|null
     */
    public function execute($request, $catchReply = false);
}

Correct description for catchReply argument.

https://github.com/Payum/Payum/pull/626


<?php

namespace Drubo\Config\Project;

use Drubo\Config\ConfigSchema;
use Drubo\DruboAwareInterface;
use Drubo\DruboAwareTrait;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Validator\Constraints\Url;
use Symfony\Component\Validator\Constraints\UrlValidator;

/**
 * Schema class for drubo project configuration files.
 */
class ProjectConfigSchema extends ConfigSchema implements ConfigurationInterface, DruboAwareInterface {

  use DruboAwareTrait;

  /**
   * {@inheritdoc}
   */
  public function getConfigTreeBuilder() {
    $treeBuilder = new TreeBuilder();
    $rootNode = $treeBuilder->root('config');

    $environmentList = $this->getDrubo()
      ->getEnvironmentList()
      ->toArray();

    $rootNode
      ->children()
        ->scalarNode('environment')
          ->isRequired()
          ->cannotBeEmpty()
          ->validate()
            ->ifNotInArray($environmentList)
            ->thenInvalid('Invalid environment %s')
          ->end()
        ->end()
        ->scalarNode('uri')
          ->isRequired()
          ->cannotBeEmpty()
          ->validate()
            ->always(function ($v) {
              // TODO Url validation
//              $x = new UrlValidator();
//              $x->validate($v, new Url());

              return $v;
            })
          ->end()
        ->end()
      ->end();

    return $treeBuilder;
  }

}

<?php

namespace Drubo\Config\Project;

use Drubo\Config\ConfigSchema;
use Drubo\DruboAwareInterface;
use Drubo\DruboAwareTrait;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Validator\Constraints\Url;

/**
 * Schema class for drubo project configuration files.
 */
class ProjectConfigSchema extends ConfigSchema implements ConfigurationInterface, DruboAwareInterface {

  use DruboAwareTrait;

  /**
   * {@inheritdoc}
   */
  public function getConfigTreeBuilder() {
    $treeBuilder = new TreeBuilder();
    $rootNode = $treeBuilder->root('config');

    $environmentList = $this->getDrubo()
      ->getEnvironmentList()
      ->toArray();

    $rootNode
      ->children()
        ->scalarNode('environment')
          ->isRequired()
          ->cannotBeEmpty()
          ->validate()
            ->ifNotInArray($environmentList)
            ->thenInvalid('Invalid environment %s')
          ->end()
        ->end()
        ->scalarNode('uri')
          ->isRequired()
          ->cannotBeEmpty()
          ->validate()
            ->always(function ($v) {
              $violations = $this->getDrubo()
                ->getValidator()
                ->validate($v, new Url());

              /** @var \Symfony\Component\Validator\ConstraintViolationInterface $violation */
              foreach ($violations as $violation) {
                throw new \Exception($violation->getMessage());
              }

              return $v;
            })
          ->end()
        ->end()
      ->end();

    return $treeBuilder;
  }

}

Validate URI in project config schema

Validate URI in project config schema


<?php

namespace Vectorface\MySQLite\MySQL;

/**
 * Provides Date and Time MySQL compatibility functions for SQLite.
 *
 * http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html
 */
trait DateTime
{
    /**
     * NOW - Return the current date and time
     *
     * @return string The current timestamp, in MySQL's date format.
     */
    public static function mysql_now()
    {
        return date("Y-m-d H:i:s");
    }

    /**
     * TO_DAYS - Return the date argument converted to days
     *
     * @param string $date A date to be converted to days.
     * @return int The date converted to a number of days since year 0.
     */
    public static function mysql_to_days($date)
    {
        return  719527 + ceil(strtotime($date) / (60 * 60 * 24));
    }

    /**
     * UNIX_TIMESTAMP - Return a UNIX timestamp
     *
     * @param string $date The date to be converted to a unix timestamp. Defaults to the current date/time.
     * @return int The number of seconds since the unix epoch.
     */
    public static function mysql_unix_timestamp($date = null)
    {
        if (!isset($date)) {
            return time();
        }

        return strtotime($date);
    }
}

<?php

namespace Vectorface\MySQLite\MySQL;

/**
 * Provides Date and Time MySQL compatibility functions for SQLite.
 *
 * http://dev.mysql.com/doc/refman/5.7/en/date-and-time-functions.html
 */
trait DateTime
{
    /**
     * NOW - Return the current date and time
     *
     * @return string The current timestamp, in MySQL's date format.
     */
    public static function mysql_now()
    {
        return date("Y-m-d H:i:s");
    }

    /**
     * TO_DAYS - Return the date argument converted to days
     *
     * @param string $date A date to be converted to days.
     * @return int The date converted to a number of days since year 0.
     */
    public static function mysql_to_days($date)
    {
        return  719527 + intval(ceil(strtotime($date) / (60 * 60 * 24)));
    }

    /**
     * UNIX_TIMESTAMP - Return a UNIX timestamp
     *
     * @param string $date The date to be converted to a unix timestamp. Defaults to the current date/time.
     * @return int The number of seconds since the unix epoch.
     */
    public static function mysql_unix_timestamp($date = null)
    {
        if (!isset($date)) {
            return time();
        }

        return strtotime($date);
    }
}

Fix return type of TO_DAYS function. Should be int.


<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;

// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);

// This check prevents access to debug front controllers that are deployed by accident to production servers.
// Feel free to remove this, extend it, or make something more sophisticated.
if (isset($_SERVER['HTTP_CLIENT_IP'])
    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
    || !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1',  '193.108.249.215')) || php_sapi_name() === 'cli-server'
    || strpos(@$_SERVER['REMOTE_ADDR'], '10.0.3.') === 0
    || strpos(@$_SERVER['REMOTE_ADDR'], '10.0.4.') === 0
  )
) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();

require_once __DIR__.'/../app/AppKernel.php';

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

<?php

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Debug\Debug;
use Symfony\Component\HttpFoundation\IpUtils;

// If you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);

$loader = require_once __DIR__.'/../app/bootstrap.php.cache';
Debug::enable();

require_once __DIR__.'/../app/AppKernel.php';

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$clientIps = $request->getClientIps();
$lastClientIp = $clientIps[count($clientIps) - 1];
if (!IpUtils::checkIp($lastClientIp, ['127.0.0.1', 'fe80::1', '::1', '193.108.249.215', '78.137.6.142', '10.0.0.0/8'])) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

Use IpUtils to check for local addresses


<?php

namespace Plummer\Calendarful\Calendar;

use Plummer\Calendarful\RegistryInterface;

interface CalendarInterface
{
	public function populate(RegistryInterface $eventsRegistry, \DateTime $fromDate, \DateTime $toDate, $limit);

	public function sort();
}

<?php

namespace Plummer\Calendarful\Calendar;

use Plummer\Calendarful\RegistryInterface;

interface CalendarInterface
{
	public function populate(RegistryInterface $eventsRegistry, \DateTime $fromDate, \DateTime $toDate, $limit = null, Array $extraFilters = array());

	public function sort();
}

Change populate method to allow limit to be null and take an extra array of filters.


<?php

namespace Droid\Loader;

use Symfony\Component\Yaml\Parser as YamlParser;
use Droid\Model\Inventory;
use Droid\Model\Host;
use Droid\Model\HostGroup;
use RuntimeException;

class YamlInventoryLoader
{
    public function load(Inventory $inventory, $filename)
    {
        if (!file_exists($filename)) {
            throw new RuntimeException("File not found: $filename");
        }

        $parser = new YamlParser();
        $data = $parser->parse(file_get_contents($filename));

        if (isset($data['hosts'])) {
            foreach ($data['hosts'] as $hostName => $hostNode) {
                $host = new Host($hostName);
                $inventory->addHost($host);
            }
        }

        if (isset($data['groups'])) {
            foreach ($data['groups'] as $groupName => $groupNode) {
                $group = new HostGroup($groupName);
                foreach ($groupNode as $hostName) {
                    if (!$inventory->hasHost($hostName)) {
                        throw new RuntimeException("Group $groupName refers to undefined host: $hostName");
                    }
                    $host = $inventory->getHost($hostName);
                    $group->addHost($host);
                }
                $inventory->addHostGroup($group);
            }
        }
        //print_r($inventory);
    }
}

<?php

namespace Droid\Loader;

use Symfony\Component\Yaml\Parser as YamlParser;
use Droid\Model\Inventory;
use Droid\Model\Host;
use Droid\Model\HostGroup;
use RuntimeException;

class YamlInventoryLoader
{
    public function load(Inventory $inventory, $filename)
    {
        if (!file_exists($filename)) {
            throw new RuntimeException("File not found: $filename");
        }

        $parser = new YamlParser();
        $data = $parser->parse(file_get_contents($filename));

        if (isset($data['hosts'])) {
            foreach ($data['hosts'] as $hostName => $hostNode) {
                $host = new Host($hostName);
                if (isset($hostNode['hostname'])) {
                    $host->setHostName($hostNode['hostname']);
                }
                $inventory->addHost($host);
            }
        }

        if (isset($data['groups'])) {
            foreach ($data['groups'] as $groupName => $groupNode) {
                $group = new HostGroup($groupName);
                foreach ($groupNode as $hostName) {
                    if (!$inventory->hasHost($hostName)) {
                        throw new RuntimeException("Group $groupName refers to undefined host: $hostName");
                    }
                    $host = $inventory->getHost($hostName);
                    $group->addHost($host);
                }
                $inventory->addHostGroup($group);
            }
        }
        //print_r($inventory);
    }
}

Support hostname argument on hosts defined in inventory.yml


<?php

namespace Naughtonium\LaravelDarkSky;

use Illuminate\Support\ServiceProvider;

class LaravelDarkSkyServiceProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        $source = dirname(__DIR__).'/config/darksky.php';

        $this->publishes([$source => config_path('darksky.php')]);

        $this->mergeConfigFrom($source, 'darksky');
    }

    /**
     * Register any package services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('darksky',function($app)
        {
            return new DarkSky();
        });
    }
}

<?php

namespace Naughtonium\LaravelDarkSky;

use Illuminate\Support\ServiceProvider;

class LaravelDarkSkyServiceProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        $source = dirname(__DIR__).'/config/darksky.php';

        if ($this->app instanceof LaravelApplication) {
            $this->publishes([$source => config_path('darksky.php')]);
        } elseif ($this->app instanceof LumenApplication) {
            $this->app->configure('darksky');
        }

        $this->mergeConfigFrom($source, 'darksky');
    }

    /**
     * Register any package services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton('darksky',function($app)
        {
            return new DarkSky();
        });
    }
}

Add support for Laravel Lumen framework

Add support for Laravel Lumen framework


<?php

namespace Telegram\Bot\Objects\Keyboard;

use Illuminate\Support\Str;
use JsonSerializable;

abstract class BaseKeyboard implements JsonSerializable
{
    protected $items;

    /**
     * Create a new object.
     *
     * @param mixed $items
     */
    public function __construct($items = [])
    {
        $this->items = $items;
    }

    abstract public static function create();

    /**
     * Create a new row in keyboard to add buttons.
     *
     * @param array $buttons
     *
     * @return BaseKeyboard
     */
    public function row(...$buttons): self
    {
        $this->items['keyboard'][] = $buttons;

        return $this;
    }

    /**
     * Dynamically build params.
     *
     * @param string $method
     * @param array  $args
     *
     * @return $this
     */
    public function __call($method, $args)
    {
        $property = Str::snake(substr($method, 3));
        $this->items[$property] = $args[0];

        return $this;
    }

    public function jsonSerialize()
    {
        return $this->items;
    }
}

<?php

namespace Telegram\Bot\Objects\Keyboard;

use Illuminate\Support\Str;
use JsonSerializable;

abstract class BaseKeyboard implements JsonSerializable
{
    protected $items;
    protected string $type;

    /**
     * Create a new object.
     *
     * @param mixed $items
     */
    public function __construct($items = [])
    {
        $this->items = $items;
        $this->type = (static::class === ReplyKeyboardMarkup::class) ? 'keyboard' : 'inline_keyboard';
    }

    abstract public static function create();

    /**
     * Create a new row in keyboard to add buttons.
     *
     * @param array $buttons
     *
     * @return BaseKeyboard
     */
    public function row(...$buttons): self
    {
        $this->items[$this->type][] = $buttons;

        return $this;
    }

    /**
     * Dynamically build params.
     *
     * @param string $method
     * @param array  $args
     *
     * @return $this
     */
    public function __call($method, $args)
    {
        $property = Str::snake(substr($method, 3));
        $this->items[$property] = $args[0];

        return $this;
    }

    public function jsonSerialize()
    {
        return $this->items;
    }
}

Fix inline and reply keyboard creation

Fix inline and reply keyboard creation


<?php

namespace BitWasp\Stratum\Request;

use BitWasp\Stratum\Exception\ApiError;

class RequestFactory
{
    /**
     * @var array
     */
    private $nonces = [];

    /**
     * @param string $method
     * @param array $params
     * @return Request
     */
    public function create($method, $params = array())
    {
        do {
            $id = mt_rand(0, PHP_INT_MAX);
        } while (in_array($id, $this->nonces));

        return new Request($id, $method, $params);
    }

    /**
     * @param $string
     * @return Response|Request
     * @throws \Exception
     */
    public function response($string)
    {
        $decoded = json_decode(trim($string), true);

        if (json_last_error() === JSON_ERROR_NONE) {
            $id = isset($decoded['id']) ? $decoded['id'] : null;

            if (isset($decoded['error'])) {
                throw new ApiError($id, $decoded['error']);
            } elseif (isset($decoded['method']) && isset($decoded['params'])) {
                return new Request($id, $decoded['method'], $decoded['params']);
            } elseif (isset($decoded['result'])) {
                return new Response($id, $decoded['result']);
            }

            throw new \Exception('Response missing error/params/result');
        }

        throw new \Exception('Invalid JSON');
    }
}

<?php

namespace BitWasp\Stratum\Request;

use BitWasp\Stratum\Exception\ApiError;

class RequestFactory
{
    /**
     * @var array
     */
    private $nonces = [];

    /**
     * @param string $method
     * @param array $params
     * @return Request
     */
    public function create($method, $params = array())
    {
        do {
            $id = mt_rand(0, PHP_INT_MAX);
        } while (in_array($id, $this->nonces));

        return new Request($id, $method, $params);
    }

    /**
     * @param $string
     * @return Response|Request
     * @throws \Exception
     */
    public function response($string)
    {
        $decoded = json_decode(trim($string), true);

        if (json_last_error() === JSON_ERROR_NONE) {
            $id = isset($decoded['id']) ? $decoded['id'] : null;

            if (isset($decoded['error'])) {
                return new ApiError($id, $decoded['error']);
            } elseif (isset($decoded['method']) && isset($decoded['params'])) {
                return new Request($id, $decoded['method'], $decoded['params']);
            } elseif (isset($decoded['result'])) {
                return new Response($id, $decoded['result']);
            }

            throw new \Exception('Response missing error/params/result');
        }

        throw new \Exception('Invalid JSON');
    }
}

Return API error during parse, since it's being sent by the remote server


<?php

namespace Criterion\Test;

class TestCase extends \PHPUnit_Framework_TestCase
{

    public function setUp()
    {
        putenv('APP_ENV=testing');
    }

}

<?php

namespace Criterion\Test;

class TestCase extends \PHPUnit_Framework_TestCase
{

    public function setUp()
    {
        putenv('APP_ENV=testing');

        $app = new \Criterion\Application();
        $app->db->drop();

        if ( ! defined('ROOT'))
        {
            define('ROOT', dirname(dirname(dirname(__DIR__))));
            define('CONFIG_FILE', ROOT . '/config.json');
            define('DATA_DIR', ROOT  . '/data');
            define('TEST_DIR', DATA_DIR . '/tests');
            define('KEY_DIR', DATA_DIR . '/keys');
        }
    }

}

Define constants, and drop DB each test setup


<?php
// (c) Copyright 2002-2011 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"],basename(__FILE__)) !== false) {
  header("location: index.php");
  exit;
}

/*
 * Smarty plugin
 * -------------------------------------------------------------
 * Type:     modifier
 * Name:     duration
 * Purpose:  formats a duration from seconds
 * -------------------------------------------------------------
 */
function smarty_modifier_duration_short($string) {
  $result='';
  if ($string > 60*60*24) {
    $days = floor($string/(60*60*24));
    $result = "$days ".tra('days');
  } elseif ($string > 60*60) {
    $hours = floor($string/(60*60));
    $result = "$hours ".tra('hours');
  } elseif ($string > 60) {
    $mins = floor($string/(60));
    $result = "$mins ".tra('minutes');
  } else {
	  $result = "$string ".tra('seconds');
  }
  return $result;
}

<?php
// (c) Copyright 2002-2011 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"],basename(__FILE__)) !== false) {
  header("location: index.php");
  exit;
}

/*
 * Smarty plugin
 * -------------------------------------------------------------
 * Type:     modifier
 * Name:     duration
 * Purpose:  formats a duration from seconds
 * -------------------------------------------------------------
 */
function smarty_modifier_duration_short($string) {
	$result='';
	if ($string > 60*60*24) {
		$days = floor($string/(60*60*24));
		$day_label = $days == 1 ? tra('day') : tra('days');
		$result = "$days " . $day_label;
	} elseif ($string > 60*60) {
		$hours = floor($string/(60*60));
		$hr_label = $hours == 1 ? tra('hour') : tra('hours');
		$result = "$hours " . $hr_label;
	} elseif ($string > 60) {
		$mins = floor($string/(60));
		$min_label = $mins == 1 ? tra('minute') : tra('minutes');
		$result = "$mins " . $min_label;
	} else {
		$sec_label = $string == 1 ? tra('second') : tra('seconds');
		$result = "$string " . $sec_label;
	}
	return $result;
}

[FIX] Use singular form for 1 day, hour, minute, or second

git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@35434 b456876b-0849-0410-b77d-98878d47e9d5


<?php

declare(strict_types=1);

namespace WRS\Tests\Storage;

use PHPUnit\Framework\TestCase;

use WRS\Storage\NullStorage;

class NullStorageTest extends TestCase
{
    const KEY = "test";
    const VALUE = "value";

    public function testSave()
    {
        $ns = new NullStorage();
        $ns->save(self::KEY, self::VALUE);
        $this->assertTrue(true);
    }

    public function testExists()
    {
        $ns = new NullStorage();
        $ns->save(self::KEY, self::VALUE);
        $this->assertSame(false, $ns->exists(self::KEY));
    }

    /**
     * @expectedException        Exception
     * @expectedExceptionMessage Cannot load key test
     */
    public function testLoad()
    {
        $ns = new NullStorage();
        $result = $ns->load(self::KEY);
    }
}

<?php

declare(strict_types=1);

namespace WRS\Tests\Storage;

use PHPUnit\Framework\TestCase;

use WRS\Storage\NullStorage;

class NullStorageTest extends TestCase
{
    const KEY = "test";
    const VALUE = "value";

    public function testSave()
    {
        $ns = new NullStorage();
        $ns->save(self::KEY, self::VALUE);
        $this->assertTrue(true);
    }

    public function testExists()
    {
        $ns = new NullStorage();
        $ns->save(self::KEY, self::VALUE);
        $this->assertSame(false, $ns->exists(self::KEY));
    }

    /**
     * @expectedException Exception
     * @expectedExceptionMessageRegExp #^Cannot load key .*$#
     */
    public function testLoad()
    {
        $ns = new NullStorage();
        $result = $ns->load(self::KEY);
    }
}

Convert message check to regex

Convert message check to regex