<?php

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

namespace App\Libraries\Markdown\StyleBlock;

use League\CommonMark\Block\Element\AbstractBlock;
use League\CommonMark\Cursor;

class Element extends AbstractBlock
{
    /**
     * @var string
     */
    protected $class;

    public function __construct(string $class)
    {
        $this->class = $class;
    }

    public function getClass(): string
    {
        return $this->class;
    }

    public function canContain(AbstractBlock $block): bool
    {
        return true;
    }

    public function isCode(): bool
    {
        return false;
    }

    public function matchesNextLine(Cursor $cursor): bool
    {
        // Make sure the most nested open StyleBlock tries to handle this first
        if ($cursor->getLine() === '}}}' && !$this->containsOpenStyleBlock()) {
            $cursor->advanceToEnd();

            return false;
        }

        return true;
    }

    private function containsOpenStyleBlock(): bool
    {
        $walker = $this->walker();
        $walker->next();

        while (($event = $walker->next()) !== null) {
            if (!$event->isEntering()) {
                continue;
            }

            $node = $event->getNode();

            if ($node instanceof static && $node->isOpen()) {
                return true;
            }
        }

        return false;
    }
}

<?php

// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0.
// See the LICENCE file in the repository root for full licence text.

namespace App\Libraries\Markdown\StyleBlock;

use League\CommonMark\Block\Element\AbstractBlock;
use League\CommonMark\Cursor;

class Element extends AbstractBlock
{
    /**
     * @var string
     */
    protected $class;

    /**
     * @var static[]
     */
    protected $containedStyleBlocks;

    public function __construct(string $class)
    {
        $this->class = $class;
        $this->containedStyleBlocks = [];
    }

    public function getClass(): string
    {
        return $this->class;
    }

    public function canContain(AbstractBlock $block): bool
    {
        if ($block instanceof static) {
            $this->containedStyleBlocks[] = $block;
        }

        return true;
    }

    public function isCode(): bool
    {
        return false;
    }

    public function matchesNextLine(Cursor $cursor): bool
    {
        // Make sure the most nested open StyleBlock tries to handle this first
        if ($cursor->getLine() === '}}}' && !$this->containsOpenStyleBlock()) {
            $cursor->advanceToEnd();

            return false;
        }

        return true;
    }

    private function containsOpenStyleBlock(): bool
    {
        // Assumes that these StyleBlocks are never removed from descendant tree
        foreach ($this->containedStyleBlocks as $styleBlock) {
            if ($styleBlock->isOpen()) {
                return true;
            }
        }

        return false;
    }
}

Store StyleBlock descendants to speed up containsOpenStyleBlock


<?php

use Symfony\Component\HttpFoundation\Request;

// 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'))
) {
    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';
require_once __DIR__.'/../app/AppKernel.php';

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

<?php

use Symfony\Component\HttpFoundation\Request;

// 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'))
) {
    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';
require_once __DIR__.'/../app/AppKernel.php';

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

Fix permissions for dev env.

Fix permissions for dev env.


<?php

namespace PhpFp\Either\Test;

use PhpFp\Either\Either;
use PhpFp\Either\Constructor\{Left, Right};

class ApTest extends \PHPUnit_Framework_TestCase
{
    public function testApParameterCount()
    {
        $count = (new \ReflectionMethod('PhpFp\Either\Constructor\Left::ap'))
            ->getNumberOfParameters();

        $this->assertEquals($count,
            1,
            'Left::ap takes one parameter.'
        );

        $count = (new \ReflectionMethod('PhpFp\Either\Constructor\Right::ap'))
            ->getNumberOfParameters();

        $this->assertEquals($count,
            1,
            'Right::ap takes one parameter.'
        );
    }

    public function testAp()
    {
        $addTwo = Either::of(
            function ($x)
            {
                return $x + 2;
            }
        );

        $id = function ($x)
        {
            return $x;
        };

        $a = Either::of(5);
        $b = new Left(4);

        $this->assertEquals(
            $addTwo
                ->ap($a)
                ->either($id, $id),
            7,
            'Applies to a Right.'
        );

        $this->assertEquals(
            $addTwo->ap($b)->either($id, $id),
            4,
            'Applies to a Left.'
        );
    }
}

<?php

namespace PhpFp\Either\Test;

use PhpFp\Either\Either;
use PhpFp\Either\Constructor\{Left, Right};

class ApTest extends \PHPUnit_Framework_TestCase
{
    public function testApParameterCount()
    {
        $count = (new \ReflectionMethod('PhpFp\Either\Constructor\Left::ap'))
            ->getNumberOfParameters();

        $this->assertEquals($count,
            1,
            'Left::ap takes one parameter.'
        );

        $count = (new \ReflectionMethod('PhpFp\Either\Constructor\Right::ap'))
            ->getNumberOfParameters();

        $this->assertEquals($count,
            1,
            'Right::ap takes one parameter.'
        );
    }

    public function testAp()
    {
        $addTwo = Either::of(
            function ($x)
            {
                return $x + 2;
            }
        );

        $id = function ($x)
        {
            return $x;
        };

        $a = Either::of(5);
        $b = new Left(4);

        $this->assertEquals(
            $addTwo
                ->ap($a)
                ->either($id, $id),
            7,
            'Applies to a Right.'
        );

        $this->assertEquals(
            $addTwo->ap($b)->either($id, $id),
            4,
            'Applies to a Left.'
        );

        $subOne = new Left(
            function ($x) {
                return $x - 1;
            }
        );

        $this->assertEquals(
            $subOne->ap($a)->either($id, $id),
            5,
            'Does not apply to a Right.'
        );

        $this->assertEquals(
            $subOne->ap($b)->either($id, $id),
            4,
            'Does not apply to a Left.'
        );
    }
}

Add missing test for Left::ap

Add missing test for Left::ap


<?php

namespace Monolol\Lolifiers;

use Monolol\Referentials\MonologLevel;
use Monolol\Lolifiers\Quote;
use Monolol\Lolifiers\QuoteProviders;
use Monolog\Logger;

class QuoteTest extends \PHPUnit_Framework_TestCase
{
    public function testHandling()
    {
        $this->assertTrue((new Quote(new QuoteProviders\EmptyQuoteProvider()))->isHandling(array()));
    }

    /**
     * @dataProvider providerTestQuote
     */
    public function testQuote(QuoteProvider $provider, $logMessage)
    {
        $record = array('message' => $logMessage, 'datetime' => new \DateTime());

        $lolifier = new Quote($provider);

        $lolilfiedRecord = $lolifier->lolify($record);

        $this->assertTrue(in_array($lolilfiedRecord['message'], $provider->getQuotes()));
    }

    public function providerTestQuote()
    {
        return array(
            'Perceval' => array(new QuoteProviders\Kaamelott\Perceval(), 'Internal Burger Error'),
            'Karadoc'  => array(new QuoteProviders\Kaamelott\Karadoc(), 'Internal Pony Error'),
            'Merlin'   => array(new QuoteProviders\Kaamelott\Merlin(), 'Internal Unicorn Error'),
            'Kadoc'    => array(new QuoteProviders\Kaamelott\Merlin(), 'Internal Rabbit Error'),
        );
    }
}

<?php

namespace Monolol\Lolifiers;

use Monolol\Referentials\MonologLevel;
use Monolol\Lolifiers\Quote;
use Monolol\Lolifiers\QuoteProviders;
use Monolog\Logger;

class QuoteTest extends \PHPUnit_Framework_TestCase
{
    public function testHandling()
    {
        $this->assertTrue((new Quote(new QuoteProviders\EmptyQuoteProvider()))->isHandling(array()));
    }

    /**
     * @dataProvider providerTestQuote
     */
    public function testQuote(QuoteProvider $provider, $logMessage)
    {
        $record = array('message' => $logMessage, 'datetime' => new \DateTime());

        $lolifier = new Quote($provider);

        $lolilfiedRecord = $lolifier->lolify($record);

        $this->assertTrue(in_array($lolilfiedRecord['message'], $provider->getQuotes()));
    }

    public function providerTestQuote()
    {
        return array(
            'Perceval' => array(new QuoteProviders\Kaamelott\Perceval(), 'Internal Burger Error'),
            'Karadoc'  => array(new QuoteProviders\Kaamelott\Karadoc(), 'Internal Pony Error'),
            'Merlin'   => array(new QuoteProviders\Kaamelott\Merlin(), 'Internal Unicorn Error'),
            'Kadoc'    => array(new QuoteProviders\Kaamelott\Kadoc(), 'Internal Rabbit Error'),
        );
    }
}

fix: Fix wrong tested quote provider in Quote test


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

Register

Our Committee

Terms

Code of Conduct

Schedule

Sponsorship

Fix case on committee URL

Fix case on committee URL


<?php

namespace RulerZ\Model;

use Hoa\Ruler\Model as HoaModel;
use RulerZ\Visitor;

class Rule extends HoaModel\Model
{
    /**
     * Returns a list of accessed variables.
     *
     * @return \Hoa\Ruler\Model\Bag\Context[]
     */
    public function getAccesses()
    {
        $visitor = new Visitor\AccessCollectorVisitor();

        return $visitor->visit($this);
    }

    /**
     * Returns a list of used operators.
     *
     * @return \Hoa\Ruler\Model\Operator[]
     */
    public function getOperators()
    {
        $visitor = new Visitor\OperatorCollectorVisitor();

        return $visitor->visit($this);
    }

    /**
     * Returns a list of used parameters.
     *
     * @return \Hoa\Ruler\Model\Parameter[]
     */
    public function getParameters()
    {
        $visitor = new Visitor\ParameterCollectorVisitor();

        return $visitor->visit($this);
    }
}

<?php

namespace RulerZ\Model;

use Hoa\Ruler\Model as HoaModel;
use RulerZ\Visitor;

class Rule extends HoaModel\Model
{
    /**
     * Returns a list of accessed variables.
     *
     * @return \Hoa\Ruler\Model\Bag\Context[]
     */
    public function getAccesses()
    {
        $visitor = new Visitor\AccessCollectorVisitor();

        return $visitor->visit($this);
    }

    /**
     * Returns a list of used operators.
     *
     * @return \Hoa\Ruler\Model\Operator[]
     */
    public function getOperators()
    {
        $visitor = new Visitor\OperatorCollectorVisitor();

        return $visitor->visit($this);
    }

    /**
     * Returns a list of used parameters.
     *
     * @return \RulerZ\Model\Parameter[]
     */
    public function getParameters()
    {
        $visitor = new Visitor\ParameterCollectorVisitor();

        return $visitor->visit($this);
    }
}

Fix incorrect phpdoc return type

Fix incorrect phpdoc return type


<?php

use Hoa\Router;

$router = new Router\Http();
$router
    ->get(
        'c',
        '(?<vendor>)/(?<chapter>)\.html'
    )
    ->get(
        'hack',
        '(?<chapter>)\.html'
    )
    ->get(
        'learn',
        'http://hoa-project.net/Literature/Learn/(?<chapter>)\.html'
    )
    ->get(
        'full',
        '/(?<vendor>)/(?<chapter>)\.html'
    )

    ->get(
        '_resource',
        'http://static.hoa-project.net/(?<resource>)'
    )
    ->_get(
        'central_resource',
        'http://central.hoa-project.net/Resource/(?<path>)'
    )
    ->_get(
        'board',
        'https://waffle.io/hoaproject/(?<repository>)'
    )
    ->_get(
        'git',
        'http://git.hoa-project.net/(?<repository>).git/'
    )
    ->_get(
        'github',
        'https://github.com/hoaproject/(?<repository>)'
    );

<?php

use Hoa\Router;

$router = new Router\Http();
$router
    ->get(
        'c',
        '(?<vendor>)/(?<chapter>)\.html'
    )
    ->get(
        'hack',
        '(?<chapter>)\.html'
    )
    ->get(
        'full',
        '/(?<vendor>)/(?<chapter>)\.html'
    )

    ->_get(
        'literature',
        'http://hoa-project.net/Literature\.html'
    )
    ->_get(
        'learn',
        'http://hoa-project.net/Literature/Learn/(?<chapter>)\.html'
    )
    ->get(
        '_resource',
        'http://static.hoa-project.net/(?<resource>)'
    )
    ->_get(
        'central_resource',
        'http://central.hoa-project.net/Resource/(?<path>)'
    )
    ->_get(
        'board',
        'https://waffle.io/hoaproject/(?<repository>)'
    )
    ->_get(
        'git',
        'http://git.hoa-project.net/(?<repository>).git/'
    )
    ->_get(
        'github',
        'https://github.com/hoaproject/(?<repository>)'
    );

Add the `literature` router rule for the doc.


<?php
/*=========================================================================
MIDAS Server
Copyright (c) Kitware SAS. 20 rue de la Villette. All rights reserved.
69328 Lyon, FRANCE.

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

/** Component for api methods */
class Slicerappstore_ApiComponent extends AppComponent
{

  /**
   * Helper function for verifying keys in an input array
   */
  private function _checkKeys($keys, $values)
    {
    foreach($keys as $key)
      {
      if(!array_key_exists($key, $values))
        {
        throw new Exception('Parameter '.$key.' must be set.', -1);
        }
      }
    }

  /**
   * Helper function to get the user from token or session authentication
   */
  private function _getUser($args)
    {
    $componentLoader = new MIDAS_ComponentLoader();
    $authComponent = $componentLoader->loadComponent('Authentication', 'api');
    return $authComponent->getUser($args, null);
    }

  /**
   * Test the web api from this plugin
   * @param foo (Optional) not used
   * @return a json object defining a foo --> bar relationship
   */
  public function test($args)
    {
      $ret = array();
      $ret['foo'] = 'bar';
      return $ret;
    } // end function test

} // end class

<?php
/*=========================================================================
MIDAS Server
Copyright (c) Kitware SAS. 20 rue de la Villette. All rights reserved.
69328 Lyon, FRANCE.

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

/** Component for api methods */
class Slicerappstore_ApiComponent extends AppComponent
{

  /**
   * Helper function for verifying keys in an input array
   */
  private function _checkKeys($keys, $values)
    {
    foreach($keys as $key)
      {
      if(!array_key_exists($key, $values))
        {
        throw new Exception('Parameter '.$key.' must be set.', -1);
        }
      }
    }

  /**
   * Helper function to get the user from token or session authentication
   */
  private function _getUser($args)
    {
    try
      {
      $componentLoader = new MIDAS_ComponentLoader();
      $authComponent = $componentLoader->loadComponent('Authentication', 'api');
      }
    catch (Zend_Exception $e)
      {
      $authComponent = MidasLoader::loadComponent('Authentication');
      }
    return $authComponent->getUser($args, null);
    }

  /**
   * Test the web api from this plugin
   * @param foo (Optional) not used
   * @return a json object defining a foo --> bar relationship
   */
  public function test($args)
    {
      $ret = array();
      $ret['foo'] = 'bar';
      return $ret;
    } // end function test

} // end class

Support new location of Authentication component.

Following Midas commit d65efd4f9, authentication component has been
moved to core. This commit ensure that the module remains compatible with
Midas independently of that backward incompatible change.


<?php

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

// Throw an exception when E_ERRORS occur to better debug the problem
function throwExceptionOnError($severity, $message, $file, $line)
{
    $errMessage = sprintf('Language error ("%s") thrown from %s:%s', $message, $file, $line);

    throw new \Exception($errMessage, $severity);
}

set_error_handler('throwExceptionOnError');

<?php

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

// Throw an exception when E_ERRORs occur to better debug the problem
function throwExceptionOnError($severity, $message, $file, $line)
{
    $errMessage = sprintf('Language error ("%s") thrown from %s:%s', $message, $file, $line);

    throw new \Exception($errMessage, $severity);
}

// If `DISABLE_WARN_EXCEPTIONS` exists, then E_ERRORs will **not** be casted into exceptions
if (!getenv('DISABLE_WARN_EXCEPTIONS')) {
    set_error_handler('throwExceptionOnError');
}

Allow disable warning to exception casts in tests


<?php

namespace Djebbz\BlogBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use  Djebbz\BlogBundle\Entity\Enquiry;
use  Djebbz\BlogBundle\Form\EnquiryType;

class PageController extends Controller
{
    public function indexAction()
    {
        return $this->render('DjebbzBlogBundle:Page:index.html.twig');
    }

    public function aboutAction()
    {
        return $this->render('DjebbzBlogBundle:Page:about.html.twig');
    }

    public function contactAction()
    {
        $enquiry = new Enquiry();
        $form = $this->createForm(new EnquiryType(), $enquiry);
        $request = $this->getRequest();

        if ($request->getMethod() == 'POST') {
            $form->bindRequest($request);

            if ($form->isValid()) {
                return $this->redirect($this->generateUrl('DjebbzBlogBundle_contact'));
            }
        }
        return $this->render('DjebbzBlogBundle:Page:contact.html.twig', array(
            'form' => $form->createView()
        ));
    }
}

<?php

namespace Djebbz\BlogBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use  Djebbz\BlogBundle\Entity\Enquiry;
use  Djebbz\BlogBundle\Form\EnquiryType;

class PageController extends Controller
{
    public function indexAction()
    {
        return $this->render('DjebbzBlogBundle:Page:index.html.twig');
    }

    public function aboutAction()
    {
        return $this->render('DjebbzBlogBundle:Page:about.html.twig');
    }

    public function contactAction()
    {
        $enquiry = new Enquiry();
        $form = $this->createForm(new EnquiryType(), $enquiry);
        $request = $this->getRequest();

        if ($request->getMethod() == 'POST') {
            $form->handleRequest($request);

            if ($form->isValid()) {
                return $this->redirect($this->generateUrl('DjebbzBlogBundle_contact'));
            }
        }
        return $this->render('DjebbzBlogBundle:Page:contact.html.twig', array(
            'form' => $form->createView()
        ));
    }
}

Fix an API change (since 2.3) that crashed form submission


<?php

/**
 * @copyright 2018 Vladimir Jimenez
 * @license   https://github.com/stakx-io/stakx/blob/master/LICENSE.md MIT
 */

namespace allejo\stakx\Filesystem;

abstract class FileExplorerMatcher
{
    /**
     * Return a matcher callable for files that have been modified after a certain timestamp.
     *
     * @param \DateTime $time
     *
     * @throws \Exception
     *
     * @return \Closure
     */
    public static function modifiedAfter(\DateTime $time)
    {
        return function (File $file) use ($time) {
            return $file->getLastModified() > $time->getTimestamp();
        };
    }
}

<?php

/**
 * @copyright 2018 Vladimir Jimenez
 * @license   https://github.com/stakx-io/stakx/blob/master/LICENSE.md MIT
 */

namespace allejo\stakx\Filesystem;

abstract class FileExplorerMatcher
{
    /**
     * Return a matcher callable for files that have been modified after a certain timestamp.
     *
     * @param \DateTime $time
     *
     * @throws \Exception
     *
     * @return \Closure
     */
    public static function modifiedAfter(\DateTime $time)
    {
        return function ($file) use ($time) {
            /** @var File|Folder $file */

            if ($file instanceof Folder) {
                return true;
            }

            return $file->getLastModified() > $time->getTimestamp();
        };
    }
}

Allow timestamp matcher to traverse into folders


<?php
return function (PHPCI\Plugin\Util\Factory $factory) {
    $factory->registerResource(
        // This function will be called when the resource is needed.
        function() {
            return array(
                'Foo' => "Stuff",
                'Bar' => "More Stuff"
            );
        },

        // In addition to the function for building the resource the system
        // also needs to be told when to load the resource. Either or both
        // of the following arguments can be used (null to ignore)

        // This resource will only be given when the argument name is:
        "ResourceArray",

        // The resource will only be given when the type hint is:
        PHPCI\Plugin\Util\Factory::TYPE_ARRAY
    );
};

<?php
return function (PHPCI\Plugin\Util\Factory $factory) {
    $factory->registerResource(
        // This function will be called when the resource is needed.
        function() {
            return array(
                'bar' => "Hello",
            );
        },
        "requiredArgument",
        null
    );
};

Update test ExamplePluginConfg.php to match test.


<?php
//ykksm will use the configuration stored in /etc/yubico/ksm/config-db.php, if that file exists. If it does not exist, the below values will be used.

if(!include '/etc/yubico/ksm/config-db.php') {
	$dbuser='ykksmreader';
	$dbpass='yourpassword';
	$basepath='';
	$dbname='ykksm';
	$dbserver='';
	$dbport='';
	$dbtype='mysql';
}

$db_dsn      = "$dbtype:dbname=$dbname;host=127.0.0.1";
$db_username = $dbuser;
$db_password = $dbpass;
$db_options  = array();
$logfacility = LOG_AUTH;
?>

<?php
//ykksm will use the configuration stored in /etc/yubico/ksm/config-db.php, if that file exists. If it does not exist, the below values will be used.

if(file_exists('/etc/yubico/ksm/config-db.php')) {
	include '/etc/yubico/ksm/config-db.php';
} else {
	$dbuser='ykksmreader';
	$dbpass='yourpassword';
	$basepath='';
	$dbname='ykksm';
	$dbserver='';
	$dbport='';
	$dbtype='mysql';
}
$db_dsn      = "$dbtype:dbname=$dbname;host=127.0.0.1";
$db_username = $dbuser;
$db_password = $dbpass;
$db_options  = array();
$logfacility = LOG_AUTH;
?>

Modify config-db.php include to check for file instead of doing a (failed) include and spamming the log files that the file doesn't exist


<?php namespace Morrislaptop\LaravelFivePackageBridges;

use ReflectionClass;

trait LaravelFivePackageBridgeTrait {

	public function boot()
	{
		$this->loadViewsFrom($this->namespace, $this->guessPackagePath() . '/views');
		$this->loadTranslationsFrom($this->namespace, $this->guessPackagePath() . '/lang');
		$this->setConfig();
		$this->app['config']->package($this->vendor . '/' . $this->namespace, $this->guessPackagePath() . '/config', $this->namespace);
	}

	protected function guessPackagePath() {
		$path = (new ReflectionClass(get_parent_class()))->getFileName();

		return realpath(dirname($path).'/../../');
	}

	protected function setConfig() {
		$config = require $this->guessPackagePath() . '/config/config.php';
		$this->app['config']->set($this->namespace, $config);
	}

}

<?php namespace Morrislaptop\LaravelFivePackageBridges;

use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\File;
use ReflectionClass;

trait LaravelFivePackageBridgeTrait {

	public function boot()
	{
		$this->loadViewsFrom($this->namespace, $this->guessPackagePath() . '/views');
		$this->loadTranslationsFrom($this->namespace, $this->guessPackagePath() . '/lang');
		$this->setConfig();
	}

	protected function guessPackagePath() {
		$path = (new ReflectionClass(get_parent_class()))->getFileName();

		return realpath(dirname($path).'/../../');
	}

	protected function setConfig() {
		$path = $this->guessPackagePath() . '/config/config.php';
		$files = App::make('files');

		if ( $files->exists($path) ) {
			$config = require $path;
			$this->app['config']->set($this->namespace, $config);
		}
	}

}

Check for config file first

Check for config file first


<?php namespace Anomaly\RelationshipFieldType;

use Anomaly\Streams\Platform\Addon\FieldType\FieldTypeModifier;
use Anomaly\Streams\Platform\Model\EloquentModel;

/**
 * Class RelationshipFieldTypeModifier
 *
 * @link          http://pyrocms.com/
 * @author        PyroCMS, Inc. <support@pyrocms.com>
 * @author        Ryan Thompson <ryan@pyrocms.com>
 * @package       Anomaly\RelationshipFieldType
 */
class RelationshipFieldTypeModifier extends FieldTypeModifier
{

    /**
     * The field type instance.
     * This is for IDE support.
     *
     * @var RelationshipFieldType
     */
    protected $fieldType;

    /**
     * Modify the value.
     *
     * @param $value
     * @return integer
     */
    public function modify($value)
    {
        if ($value instanceof EloquentModel) {
            return $value->getId();
        }

        return (int)$value;
    }
}

<?php namespace Anomaly\RelationshipFieldType;

use Anomaly\Streams\Platform\Addon\FieldType\FieldTypeModifier;
use Anomaly\Streams\Platform\Model\EloquentModel;

/**
 * Class RelationshipFieldTypeModifier
 *
 * @link          http://pyrocms.com/
 * @author        PyroCMS, Inc. <support@pyrocms.com>
 * @author        Ryan Thompson <ryan@pyrocms.com>
 * @package       Anomaly\RelationshipFieldType
 */
class RelationshipFieldTypeModifier extends FieldTypeModifier
{

    /**
     * The field type instance.
     * This is for IDE support.
     *
     * @var RelationshipFieldType
     */
    protected $fieldType;

    /**
     * Modify the value.
     *
     * @param $value
     * @return integer
     */
    public function modify($value)
    {
        if ($value instanceof EloquentModel) {
            return $value->getId();
        }

        return (int)$value;
    }

    /**
     * Restore the value from storage format.
     *
     * @param  $value
     * @return mixed
     */
    public function restore($value)
    {
        return $value ?: null;
    }
}

Fix issue with null value in tables

Fix issue with null value in tables


<?php
/**
 * @author         Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright      (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Core / Model
 */

namespace PH7;

class GeoIpCoreModel extends Framework\Mvc\Model\Engine\Model
{

    /*
     *  In developing
     */

    public function getCountry($sWhere)
    {
        return $this->orm->select('GeoCountry', 'countryId, countryTitle')->find('countryId', $sWhere)->orderBy('countryTitle')->execute();
    }

    public function getState($sWhere)
    {
        return $this->orm->select('GeoState', 'stateId, stateTitle')->find('stateId', $sWhere)->orderBy('stateTitle')->execute();
    }

    public function getCity($sWhere)
    {
        return $this->orm->select('GeoCity', 'cityId, cityTitle')->find('cityId', $sWhere)->orderBy('cityTitle')->execute();
    }

}

<?php
/**
 * @author         Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright      (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Core / Model
 */

namespace PH7;

class GeoIpCoreModel extends Framework\Mvc\Model\Engine\Model
{
    /*
     *  In development. Feel free to help me! <https://github.com/pH7Software/pH7-Social-Dating-CMS>
     */

    public function getCountry($sWhere)
    {
        return $this->orm->select('GeoCountry', 'countryId, countryTitle')->find('countryId', $sWhere)->orderBy('countryTitle')->execute();
    }

    public function getState($sWhere)
    {
        return $this->orm->select('GeoState', 'stateId, stateTitle')->find('stateId', $sWhere)->orderBy('stateTitle')->execute();
    }

    public function getCity($sWhere)
    {
        return $this->orm->select('GeoCity', 'cityId, cityTitle')->find('cityId', $sWhere)->orderBy('cityTitle')->execute();
    }

}

Add Github link for contributing

Add Github link for contributing


<?php

use Phinx\Migration\AbstractMigration;

class AppearanceLastClearedNull extends AbstractMigration {
	public function up() {
		$this->table('appearances')
			->changeColumn('last_cleared', 'timestamp', [ 'timezone' => true, 'null' => true, 'default' => null ]);
	}
	public function down() {
		$this->table('appearances')
			->changeColumn('last_cleared', 'timestamp', [ 'timezone' => true, 'null' => true, 'default' => 'CURRENT_TIMESTAMP' ]);
	}
}

<?php

use Phinx\Migration\AbstractMigration;

class AppearanceLastClearedNull extends AbstractMigration {
	public function up() {
		$this->table('appearances')
			->changeColumn('last_cleared', 'timestamp', [ 'timezone' => true, 'null' => true, 'default' => null ])
			->update();
	}
	public function down() {
		$this->table('appearances')
			->changeColumn('last_cleared', 'timestamp', [ 'timezone' => true, 'null' => true, 'default' => 'CURRENT_TIMESTAMP' ])
			->update();
	}
}

Add missing update calls to AppearanceLastClearedNull


<?php

namespace Nwidart\Modules\Repositories;

use Nwidart\Modules\Exceptions\Repositories\ActionFailed;
use Nwidart\Modules\Exceptions\Repositories\NoRecordsFound;

trait PerformsActions
{
    /**
     * Validate a database action such as create, update, or delete.
     *
     * @param string $action
     * @param mixed $result
     */
    protected function validateAction(string $action, $result)
    {
        if (! is_array($result)) {
            return;
        }

        // Action result instance is invalid
        if (count($result) > 1 && is_null($result[1])) {
            throw NoRecordsFound::emptyResult();
        }

        // Action itself failed to make any changes
        if ($result[0] === false) {
            throw ActionFailed::create($action);
        }
    }

    /**
     * Get the actual record from the action result.
     *
     * @param mixed $result
     * @param string|null $action
     *
     * @return mixed
     */
    protected function extractActionResult($result, $action = null)
    {
        if ($action == 'delete') {
            return $result[0];
        }

        return $result[1];
    }

    /**
     * Perform a database action.
     *
     * @param string $action
     * @param array $parameters
     *
     * @return mixed
     */
    protected function performAction(string $action, ...$parameters)
    {
        $result = parent::$action(...$parameters);

        $this->validateAction($action, $result);

        return $this->extractActionResult($result, $action);
    }
}

<?php

namespace Nwidart\Modules\Repositories;

use Nwidart\Modules\Exceptions\Repositories\ActionFailed;
use Nwidart\Modules\Exceptions\Repositories\NoRecordsFound;

trait PerformsActions
{
    /**
     * Validate a database action such as create, update, or delete.
     *
     * @param string $action
     * @param mixed $result
     */
    protected function validateAction(string $action, $result)
    {
        if (! is_array($result)) {
            return;
        }

        // Action result instance is invalid
        if (count($result) > 1 && is_null($result[1])) {
            throw NoRecordsFound::emptyResult();
        }

        // Action itself failed to make any changes
        if ($result[0] === false) {
            throw ActionFailed::create($action);
        }
    }

    /**
     * Get the actual record from the action result.
     *
     * @param mixed $result
     * @param string|null $action
     *
     * @return mixed
     */
    protected function extractActionResult($result, $action = null)
    {
        if ($action == 'delete') {
            return $result[0];
        }

        return $result[1];
    }

    /**
     * Perform a database action.
     *
     * @param string $action
     * @param array $parameters
     *
     * @return mixed
     */
    protected function performAction(string $action, ...$parameters)
    {
        $result = parent::$action(...$parameters);

        $this->validateAction($action, $result);

        $result = $this->extractActionResult($result, $action);

        return $this->convertToEntityResult($result);
    }
}

Convert Eloquent models to entities when performing an action


<?php

namespace PureMachine\Bundle\WebServiceBundle\Tests\Service;

use PureMachine\Bundle\WebServiceBundle\Service\WebServiceManager;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

/**
 * @code
 * phpunit -v -c app vendor/puremachine/ws/src/PureMachine/Bundle/WebServiceBundle/Tests/Service/DocumentationManagerTest.php
 * @endcode
 */
class DocumentationManagerTest extends WebTestCase
{

    /**
     * Checks if the addService method for a given service will not try to parse
     * and add method without the main webservice annotation
     *
     * @code
     * phpunit -v --filter testWSReference -c app vendor/puremachine/ws/src/PureMachine/Bundle/WebServiceBundle/Tests/Service/DocumentationManagerTest.php
     * @endcode
     */
    public function testWSReference()
    {
        $symfony = static::createClient();
        $wsManager = $symfony->getContainer()->get('pureMachine.sdk.webServiceManager');

        $answer = $wsManager->call('PureMachine/Doc/WSReference','PureBilling/Charge/Capture');

        print $answer->getAnswer();
    }

}

<?php

namespace PureMachine\Bundle\WebServiceBundle\Tests\Service;

use PureMachine\Bundle\WebServiceBundle\Service\WebServiceManager;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

/**
 * @code
 * phpunit -v -c app vendor/puremachine/ws/src/PureMachine/Bundle/WebServiceBundle/Tests/Service/DocumentationManagerTest.php
 * @endcode
 */
class DocumentationManagerTest extends WebTestCase
{

    /**
     * Checks if the addService method for a given service will not try to parse
     * and add method without the main webservice annotation
     *
     * @code
     * phpunit -v --filter testWSReference -c app vendor/puremachine/ws/src/PureMachine/Bundle/WebServiceBundle/Tests/Service/DocumentationManagerTest.php
     * @endcode
     */
    public function testWSReference()
    {
        $symfony = static::createClient();
        $wsManager = $symfony->getContainer()->get('pureMachine.sdk.webServiceManager');

        $answer = $wsManager->call('PureMachine/Doc/WSReference','PureBilling/Charge/Capture');

        //FIXME: not finished
    }

}

Remove a print in a unit test. sorry....


<?php

namespace Doctrine\Tests\Common\Cache;

use Doctrine\Common\Cache\Cache;
use Doctrine\Common\Cache\PredisCache;
use Predis\Client;
use Predis\Connection\ConnectionException;

class PredisCacheTest extends CacheTest
{
    private $client;

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

        try {
            $this->client->connect();
        } catch (ConnectionException $e) {
            $this->markTestSkipped('The ' . __CLASS__ .' requires the use of redis');
        }
    }

    public function testHitMissesStatsAreProvided()
    {
        $cache = $this->_getCacheDriver();
        $stats = $cache->getStats();

        $this->assertNotNull($stats[Cache::STATS_HITS]);
        $this->assertNotNull($stats[Cache::STATS_MISSES]);
    }

    /**
     * @return PredisCache
     */
    protected function _getCacheDriver()
    {
        return new PredisCache($this->client);
    }

    /**
     * {@inheritDoc}
     *
     * @dataProvider falseCastedValuesProvider
     */
    public function testFalseCastedValues($value)
    {
        if (array() === $value) {
            $this->markTestIncomplete(
                'Predis currently doesn\'t support saving empty array values. '
                . 'See https://github.com/nrk/predis/issues/241'
            );
        }

        parent::testFalseCastedValues($value);
    }
}

<?php

namespace Doctrine\Tests\Common\Cache;

use Doctrine\Common\Cache\Cache;
use Doctrine\Common\Cache\PredisCache;
use Predis\Client;
use Predis\Connection\ConnectionException;

class PredisCacheTest extends CacheTest
{
    private $client;

    public function setUp()
    {
        if (!class_exists('Predis\Client')) {
            $this->markTestSkipped('Predis\Client is missing. Make sure to "composer install" to have all dev dependencies.');
        }

        $this->client = new Client();

        try {
            $this->client->connect();
        } catch (ConnectionException $e) {
            $this->markTestSkipped('The ' . __CLASS__ .' requires the use of redis');
        }
    }

    public function testHitMissesStatsAreProvided()
    {
        $cache = $this->_getCacheDriver();
        $stats = $cache->getStats();

        $this->assertNotNull($stats[Cache::STATS_HITS]);
        $this->assertNotNull($stats[Cache::STATS_MISSES]);
    }

    /**
     * @return PredisCache
     */
    protected function _getCacheDriver()
    {
        return new PredisCache($this->client);
    }

    /**
     * {@inheritDoc}
     *
     * @dataProvider falseCastedValuesProvider
     */
    public function testFalseCastedValues($value)
    {
        if (array() === $value) {
            $this->markTestIncomplete(
                'Predis currently doesn\'t support saving empty array values. '
                . 'See https://github.com/nrk/predis/issues/241'
            );
        }

        parent::testFalseCastedValues($value);
    }
}

Check for Predis\Client existance before running tests.


<?php

namespace Da\ProtoBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class DaProtoBundle extends Bundle
{
}

<?php

namespace Da\ProtoBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;
use Da\ProtoBundle\DependencyInjection\DaProtoExtension;

class DaProtoBundle extends Bundle
{
    public function __construct()
    {
        $this->extension = new DaProtoExtension();
    }
}

Allow to change the alias of the bundle

Allow to change the alias of the bundle


<?php

namespace MockaTests\Mocka;
use Mocka;

class ClassTraitTest extends \PHPUnit_Framework_TestCase {

    public function testCallMockedMethod() {
        $mocka = new Mocka();
        /** @var \MockaMocks\AbstractClass $object */
        $object = $mocka->mockObject('\MockaMocks\AbstractClass');
        $this->assertNull($object->foo());
        $this->assertSame('foo', $object->bar());
    }

}

<?php

namespace MockaTests\Mocka;
use Mocka;

class ClassTraitTest extends \PHPUnit_Framework_TestCase {

    public function testCallMockedMethod() {
        $mocka = new Mocka();
        $className = $mocka->mockClass('\MockaMocks\AbstractClass');
        /** @var \MockaMocks\AbstractClass $object */
        $object = new $className();
        $this->assertNull($object->foo());
        $this->assertSame('foo', $object->bar());

    }

}

Use mockClass instead of mockObject

Use mockClass instead of mockObject


<?php

require_once 'HTMLPurifier/AttrDef.php';
require_once 'HTMLPurifier/AttrDef/Pixels.php';

class HTMLPurifier_AttrDef_Length extends HTMLPurifier_AttrDef_Pixels
{

    function validate($string, $config, &$context) {

        $string = trim($string);
        if ($string === '') return false;

        $parent_result = parent::validate($string, $config, $context);
        if ($parent_result !== false) return $parent_result;

        $length = strlen($string);
        $last_char = $string[$length - 1];

        if ($last_char !== '%') return false;

        $points = substr($string, 0, $length - 1);

        if (!is_numeric($points)) return false;

        $points = (int) $points;

        if ($points < 0) return '0%';
        if ($points > 100) return '100%';

        return ((string) $points) . '%';

    }

}

?>

<?php

require_once 'HTMLPurifier/AttrDef.php';
require_once 'HTMLPurifier/AttrDef/Pixels.php';

/**
 * Validates the HTML type length (not to be confused with CSS's length).
 *
 * This accepts integer pixels or percentages as lengths for certain
 * HTML attributes. Don't use this for CSS: that's
 * HTMLPurifier_AttrDef_CSSLength which requires prefixes and allows a lot
 * more different types.
 */

class HTMLPurifier_AttrDef_Length extends HTMLPurifier_AttrDef_Pixels
{

    function validate($string, $config, &$context) {

        $string = trim($string);
        if ($string === '') return false;

        $parent_result = parent::validate($string, $config, $context);
        if ($parent_result !== false) return $parent_result;

        $length = strlen($string);
        $last_char = $string[$length - 1];

        if ($last_char !== '%') return false;

        $points = substr($string, 0, $length - 1);

        if (!is_numeric($points)) return false;

        $points = (int) $points;

        if ($points < 0) return '0%';
        if ($points > 100) return '100%';

        return ((string) $points) . '%';

    }

}

?>

Make note that this is HTML specific.

Make note that this is HTML specific.

git-svn-id: 25f448894bd6eb0cddf10ded73b4f5a7ea3203f3@233 48356398-32a2-884e-a903-53898d9a118a


Add a note stating the trailing slash is required


<?php

namespace Krixon\URL;

class PortNumber
{
    private $number;

    /**
     * @param int $value
     *
     * @throws \InvalidArgumentException
     */
    public function __construct($value)
    {
        $options = [
            'options' => [
                'min_range' => 0,
                'max_range' => 65535,
            ],
        ];

        if (!filter_var($value, FILTER_VALIDATE_INT, $options)) {
            throw new \InvalidArgumentException('Invalid port number.');
        }
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return $this->toString();
    }

    /**
     * @return string
     */
    public function toString()
    {
        return (string)$this->toInt();
    }

    /**
     * @return int
     */
    public function toInt()
    {
        return $this->number;
    }
}

<?php

namespace Krixon\URL;

class PortNumber
{
    private $number;

    /**
     * @param int $value
     *
     * @throws \InvalidArgumentException
     */
    public function __construct($value)
    {
        $options = [
            'options' => [
                'min_range' => 0,
                'max_range' => 65535,
            ],
        ];

        if (!filter_var($value, FILTER_VALIDATE_INT, $options)) {
            throw new \InvalidArgumentException('Invalid port number.');
        }

        $this->number = $value;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return $this->toString();
    }

    /**
     * @return string
     */
    public function toString()
    {
        return (string)$this->toInt();
    }

    /**
     * @return int
     */
    public function toInt()
    {
        return $this->number;
    }
}

Make sure port number is stored correctly


<?php

/**
 * Functions
 *
 * @package GrottoPress\Jentil
 * @since 0.1.0
 *
 * @see https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @author GrottoPress <info@grottopress.com>
 * @author N Atta Kusi Adusei
 */

declare (strict_types = 1);

/**
 * Autoloader
 *
 * @since 0.1.0
 */
(function (string $basePath) {
    $path = $basePath.'/vendor/autoload.php';

    \file_exists($path) && require($path);
})(__DIR__);

/**
 * Run this theme.
 *
 * @action after_setup_theme
 *
 * @since 0.1.0
 */
\add_action('after_setup_theme', function () {
    \Jentil()->run();
}, 0);

<?php

/**
 * Functions
 *
 * @package GrottoPress\Jentil
 * @since 0.1.0
 *
 * @see https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @author GrottoPress <info@grottopress.com>
 * @author N Atta Kusi Adusei
 */

declare (strict_types = 1);

/**
 * Autoloader
 *
 * @since 0.1.0
 */
require __DIR__.'/vendor/autoload.php';

/**
 * Run this theme.
 *
 * @action after_setup_theme
 *
 * @since 0.1.0
 */
\add_action('after_setup_theme', function () {
    \Jentil()->run();
}, 0);

Revert conditional require of autoloader

If using Jentil as parent theme, Jentil is supposed to be installed
via `composer create-project`, in which case the autoloader would
exist in Jentil's root.

If installed as a package, it's supposed to be installed from
the consuming theme's root (eg: `wp-content/themes/my-theme),
and not from the web root.

In this case, Jentil's autoloader would not exist, but we
shouldn't get an error because Jentil's functions.php would not
be loaded.


<?php

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

namespace Behat\Behat\Tester\Result;

use Behat\Behat\Definition\SearchResult;

/**
 * Represents a skipped step result.
 *
 * @author Konstantin Kudryashov <ever.zet@gmail.com>
 */
final class SkippedStepResult implements StepResult, DefinedStepResult
{
    /**
     * @var SearchResult
     */
    private $searchResult;

    /**
     * Initializes step result.
     *
     * @param SearchResult $searchResult
     */
    public function __construct(SearchResult $searchResult)
    {
        $this->searchResult = $searchResult;
    }

    /**
     * {@inheritdoc}
     */
    public function getStepDefinition()
    {
        return $this->searchResult->getMatchedDefinition();
    }

    /**
     * {@inheritdoc}
     */
    public function isPassed()
    {
        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function getResultCode()
    {
        return self::SKIPPED;
    }
}

<?php

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

namespace Behat\Behat\Tester\Result;

use Behat\Behat\Definition\SearchResult;

/**
 * Represents a skipped step result.
 *
 * @author Konstantin Kudryashov <ever.zet@gmail.com>
 */
final class SkippedStepResult implements StepResult, DefinedStepResult
{
    /**
     * @var SearchResult
     */
    private $searchResult;

    /**
     * Initializes step result.
     *
     * @param SearchResult $searchResult
     */
    public function __construct(SearchResult $searchResult)
    {
        $this->searchResult = $searchResult;
    }

    /**
     * Returns definition search result.
     *
     * @return SearchResult
     */
    public function getSearchResult()
    {
        return $this->searchResult;
    }

    /**
     * {@inheritdoc}
     */
    public function getStepDefinition()
    {
        return $this->searchResult->getMatchedDefinition();
    }

    /**
     * {@inheritdoc}
     */
    public function isPassed()
    {
        return false;
    }

    /**
     * {@inheritdoc}
     */
    public function getResultCode()
    {
        return self::SKIPPED;
    }
}

Allow searchResult to be accessed after a skipped test

I'm writing a custom formatter to get the arguments passed into a test. With an ExecutedStepResult I can just find these in the searchResult attribute, but I can't do the same with the SkippedStepResult class.


Podcasts

  <?php foreach($podcasts as $podcast): ?>

        <?php echo link_to_with_icon($podcast->getTitle(), "web", $podcast->getUri()); ?>

            <?php echo link_to_with_icon('Edit', "cog", 'podcast/edit?id='.$podcast->getId()); ?>
            <?php echo link_to_with_icon('Add episode', "add", 'episode/add?podcast_id='.$podcast->getId()); ?>

  <?php endforeach; ?>
  <?php if($sf_user->isAuthenticated()): ?>

<?php echo link_to_with_icon('New podcast…', "add", 'podcast/add'); ?>

  <?php endif; ?>

Podcasts

  <?php foreach($podcasts as $podcast): ?>

        <?php echo link_to_with_icon($podcast->getTitle(), "cog", 'podcast/edit?id='.$podcast->getId()); ?>

            <?php echo link_to_with_icon('Add episode', "add", 'episode/add?podcast_id='.$podcast->getId()); ?>

  <?php endforeach; ?>

<?php echo link_to_with_icon('New podcast…', "add", 'podcast/add'); ?>

Change homepage to match spec.

Change homepage to match spec.


<?php

return [
    'dashboard' => 'Dashboard',

    'total_earned' => 'Total Earned',
    'total_spent' => 'Total Spent',
    'most_expensive_tag' => 'Most Expensive Tag',
    'most_expensive_day' => 'Most Expensive Day',

    'analysis' => 'Analysis',

    'recent' => 'Recent',

    'profile' => 'Profile',
    'account' => 'Account',
    'preferences' => 'Preferences',

    'empty_state' => 'There aren\'t any :resource yet'
];

<?php

return [
    'dashboard' => 'Dashboard',

    'balance' => 'Balance',
    'recurrings' => 'Recurrings',
    'left_to_spend' => 'Left to Spend',
    'total_earned' => 'Total Earned',
    'total_spent' => 'Total Spent',
    'most_expensive_tag' => 'Most Expensive Tag',
    'most_expensive_day' => 'Most Expensive Day',

    'analysis' => 'Analysis',

    'recent' => 'Recent',

    'profile' => 'Profile',
    'account' => 'Account',
    'preferences' => 'Preferences',

    'empty_state' => 'There aren\'t any :resource yet'
];

Add English translation for new cards on dashboard


<?php

namespace fieldwork\validators;

class CheckboxFieldValidator extends FieldValidator
{

    private $checked;

    public function __construct ($checked, $errorMsg)
    {
        parent::__construct($errorMsg);
        $this->checked = $checked;
    }

    public function getJsonData ()
    {
        return array_merge(parent::getJsonData(), array(
            'checked' => $this->checked
        ));
    }

    public function isValid ($value)
    {
        return $this->checked = ($value == 'on');
    }

    public function describeObject ()
    {
        return 'checkbox';
    }

}

<?php

namespace fieldwork\validators;

class CheckboxFieldValidator extends FieldValidator
{

    private $checked;

    public function __construct ($checked, $errorMsg)
    {
        parent::__construct($errorMsg);
        $this->checked = $checked;
    }

    public function getJsonData ()
    {
        return array_merge(parent::getJsonData(), array(
            'checked' => $this->checked
        ));
    }

    public function isValid ($value)
    {
        return $this->checked === ($value === 'on');
    }

    public function describeObject ()
    {
        return 'checkbox';
    }

}

Fix bug with checkbox sanitizer

Fix bug with checkbox sanitizer


<?php
class Vpc_Abstract_Image_Trl_Form_ImageData extends Vpc_Abstract_Image_Trl_ImageData
{
    public function load($row)
    {
        $src = $this->_getImageUrl($row->component_id);
        if ($src) {
            return "<img src=\"$src\" />";
        }
        return '';
    }
}

class Vpc_Abstract_Image_Trl_Form extends Vpc_Abstract_Composite_Trl_Form
{
    protected function _initFields()
    {
        parent::_initFields();

        $imageCaption = Vpc_Abstract::getSetting(
            Vpc_Abstract::getSetting($this->getClass(), 'masterComponentClass'),
            'imageCaption'
        );
        if ($imageCaption) {
            $this->add(new Vps_Form_Field_TextField('image_caption', trlVps('Image caption')));
        }

        $this->add(new Vps_Form_Field_ShowField('image', trlVps('Master Image')))
            ->setData(new Vpc_Abstract_Image_Trl_Form_ImageData());
        $fs = $this->add(new Vps_Form_Container_FieldSet(trlVps('Own Image')));
        $fs->setCheckboxToggle(true);
        $fs->setCheckboxName('own_image');
        $fs->add(Vpc_Abstract_Form::createChildComponentForm($this->getClass(), '-image', 'image'));
    }
}

<?php
class Vpc_Abstract_Image_Trl_Form_ImageData extends Vpc_Abstract_Image_Trl_ImageData
{
    public function load($row)
    {
        $src = $this->_getImageUrl($row->component_id);
        if ($src) {
            return "<img src=\"$src\" />";
        }
        return '';
    }
}

class Vpc_Abstract_Image_Trl_Form extends Vpc_Abstract_Form //nicht von Vpc_Abstract_Composite_Trl_Form, da sonst die felder doppelt eingefügt werden
{
    protected function _initFields()
    {
        parent::_initFields();

        $imageCaption = Vpc_Abstract::getSetting(
            Vpc_Abstract::getSetting($this->getClass(), 'masterComponentClass'),
            'imageCaption'
        );
        if ($imageCaption) {
            $this->add(new Vps_Form_Field_TextField('image_caption', trlVps('Image caption')));
        }

        $this->add(new Vps_Form_Field_ShowField('image', trlVps('Master Image')))
            ->setData(new Vpc_Abstract_Image_Trl_Form_ImageData());
        $fs = $this->add(new Vps_Form_Container_FieldSet(trlVps('Own Image')));
        $fs->setCheckboxToggle(true);
        $fs->setCheckboxName('own_image');
        $fs->add(Vpc_Abstract_Form::createChildComponentForm($this->getClass(), '-image', 'image'));
    }
}

Fix dass bei News Detail Preview Image Admin felder doppelt waren


<?php

namespace Backend\Modules\MediaLibrary\Api;

use Backend\Modules\MediaLibrary\Domain\MediaItem\MediaItemRepository;
use FOS\RestBundle\Controller\Annotations as Rest;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Serializer\SerializerInterface;

final class AssetController
{
    /** @var MediaItemRepository */
    private $mediaItemRepository;

    /** @var SerializerInterface */
    private $serializer;

    public function __construct(MediaItemRepository $mediaItemRepository, SerializerInterface $serializer)
    {
        $this->mediaItemRepository = $mediaItemRepository;
        $this->serializer = $serializer;
    }

    /**
     * @Rest\Get("/medialibrary/asset/{uuid}")
     */
    public function getAssetAction(string $uuid): JsonResponse
    {
        return JsonResponse::fromJsonString(
            $this->serializer->serialize($this->mediaItemRepository->find($uuid), 'json')
        );
    }
}

<?php

namespace Backend\Modules\MediaLibrary\Api;

use Backend\Modules\MediaLibrary\Domain\MediaItem\MediaItem;
use Backend\Modules\MediaLibrary\Domain\MediaItem\MediaItemRepository;
use FOS\RestBundle\Controller\Annotations as Rest;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Serializer\SerializerInterface;

final class AssetController
{
    /** @var MediaItemRepository */
    private $mediaItemRepository;

    /** @var SerializerInterface */
    private $serializer;

    public function __construct(MediaItemRepository $mediaItemRepository, SerializerInterface $serializer)
    {
        $this->mediaItemRepository = $mediaItemRepository;
        $this->serializer = $serializer;
    }

    /**
     * @Rest\Get("/medialibrary/asset/{uuid}")
     */
    public function getAssetAction(string $uuid): JsonResponse
    {
        return JsonResponse::fromJsonString(
            $this->serializer->serialize($this->mediaItemRepository->find($uuid), 'json')
        );
    }

    /**
     * @Rest\Get("/medialibrary/asset/{uuid}/download")
     */
    public function downloadAssetAction(string $uuid)
    {
        $mediaItem = $this->mediaItemRepository->find($uuid);

        if (!$mediaItem instanceof MediaItem) {
            throw new NotFoundHttpException();
        }

        $response = new Response();

        // Set headers
        $response->headers->set('Cache-Control', 'private');
        $response->headers->set('Content-type', mime_content_type($mediaItem->getAbsolutePath()));
        $response->headers->set(
            'Content-Disposition',
            'attachment; filename="' . basename($mediaItem->getAbsolutePath()) . '";'
        );
        $response->headers->set('Content-length', filesize($mediaItem->getAbsolutePath()));

        // Send headers before outputting anything
        $response->sendHeaders();

        $response->setContent(file_get_contents($mediaItem->getAbsolutePath()));

        return $response;
    }
}

Add endpoint to force asset download

Add endpoint to force asset download


<?php namespace GeneaLabs\LaravelCaffeine\Http\Middleware;

use Closure;

class LaravelCaffeineDripMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $content = null;
        $response = $next($request);

        if (! method_exists($response, 'getOriginalContent')) {
            return $response;
        }

        $content = $response->getOriginalContent();

        if (method_exists($content, 'render')) {
            $content = $content->render();
        }

        if (is_string($content) && strpos($content, '_token')) {
            $content = str_replace('', "", $content);
            $response->setContent($content);
        }

        return $response;
    }
}

<?php namespace GeneaLabs\LaravelCaffeine\Http\Middleware;

use Closure;

class LaravelCaffeineDripMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $content = null;
        $response = $next($request);

        if (! method_exists($response, 'getOriginalContent')) {
            return $response;
        }

        $content = $response->getOriginalContent();

        if (method_exists($content, 'render')) {
            $content = $content->render();
        }

        if (is_string($content)
            && (strpos($content, '_token')
                || (preg_match("\<meta name=[\"\']csrf[_-]token[\"\']", $content)))) {
            $newContent = "";
            $content = str_replace('', $newContent, $content);
            $response->setContent($content);
        }

        return $response;
    }
}

Fix url, add X-Request-With, organize code


<?php namespace TmlpStats\Reports\Arrangements;

class TeamMembersByQuarter extends BaseArrangement
{
    /*
     * Builds an array of TDO attendance for each team member
     */
    public function build($data)
    {
        $teamMembersData = $data['teamMembersData'];

        $reportData = [];
        foreach ($teamMembersData as $data) {

            $index = $data->withdrawCodeId !== null
                ? 'withdrawn'
                : "team{$data->teamMember->teamYear}";

            $reportData[$index]["Q{$data->teamMember->quarterNumber}"][] = $data;
        }

        return compact('reportData');
    }
}

<?php namespace TmlpStats\Reports\Arrangements;

class TeamMembersByQuarter extends BaseArrangement
{
    /*
     * Builds an array of TDO attendance for each team member
     */
    public function build($data)
    {
        $teamMembersData = $data['teamMembersData'];

        $reportData = [
            'team1'     => [],
            'team2'     => [],
            'withdrawn' => [],
        ];

        foreach ($teamMembersData as $data) {

            $index = $data->withdrawCodeId !== null
                ? 'withdrawn'
                : "team{$data->teamMember->teamYear}";

            $reportData[$index]["Q{$data->teamMember->quarterNumber}"][] = $data;
        }

        return compact('reportData');
    }
}

Fix people transfer when previous week was empty


<?php

namespace Orchestra\Tenanti\Console;

use Symfony\Component\Console\Input\InputArgument;

class TinkerCommand extends BaseCommand
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'tenanti:tinker';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Run tinker using tenant connection';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $arguments = $this->getArgumentsWithDriver('id');

        \tap($this->tenantDriver($arguments['driver']), static function ($tenanti) use ($arguments) {
            $tenanti->asDefaultConnection(
                $tenanti->getModel()->findOrFail($arguments['id']), 'tinker'
            );
        });

        $this->call('tinker');

        return 0;
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return [
            ['driver', InputArgument::OPTIONAL, 'Tenant driver name.'],
            ['id', InputArgument::OPTIONAL, 'The entity ID.'],
        ];
    }
}

<?php

namespace Orchestra\Tenanti\Console;

use Symfony\Component\Console\Input\InputArgument;

class TinkerCommand extends BaseCommand
{
    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'tenanti:tinker';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Run tinker using tenant connection';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $arguments = $this->getArgumentsWithDriver('id');

        \tap($this->tenantDriver($arguments['driver']), static function ($tenanti) use ($arguments) {
            $tenanti->asDefaultConnection(
                $tenanti->model()->findOrFail($arguments['id']), 'tinker'
            );
        });

        $this->call('tinker');

        return 0;
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return [
            ['driver', InputArgument::OPTIONAL, 'Tenant driver name.'],
            ['id', InputArgument::OPTIONAL, 'The entity ID.'],
        ];
    }
}

Fix Call to undefined method Orchestra\Tenanti\Migrator\Factory::getModel()

- Call model method instead of getModel


<?php

namespace GoalioForgotPassword\Form;

use Laminas\Form\Form;
use Laminas\Form\Element;
use GoalioForgotPassword\Options\ForgotOptionsInterface;

class Reset extends Form
{
    /**
     * @var ForgotOptionsInterface
     */
    protected $forgotOptions;

    public function __construct($name = null, ForgotOptionsInterface $forgotOptions)
    {
        $this->setForgotOptions($forgotOptions);
        parent::__construct($name);

        $this->add(array(
            'name' => 'newCredential',
            'options' => array(
                'label' => 'New Password',
            ),
            'attributes' => array(
                'type' => 'password',
            ),
        ));

        $this->add(array(
            'name' => 'newCredentialVerify',
            'options' => array(
                'label' => 'Verify New Password',
            ),
            'attributes' => array(
                'type' => 'password',
            ),
        ));

        $submitElement = new Element\Button('submit');
        $submitElement
            ->setLabel('Set new password')
            ->setAttributes(array(
                'type'  => 'submit',
            ));

        $this->add($submitElement, array(
            'priority' => -100,
        ));

    }

    public function setForgotOptions(ForgotOptionsInterface $forgotOptions)
    {
        $this->forgotOptions = $forgotOptions;
        return $this;
    }

    public function getForgotOptions()
    {
        return $this->forgotOptions;
    }
}

<?php

namespace GoalioForgotPassword\Form;

use Laminas\Form\Form;
use Laminas\Form\Element;
use GoalioForgotPassword\Options\ForgotOptionsInterface;

class Reset extends Form
{
    /**
     * @var ForgotOptionsInterface
     */
    protected $forgotOptions;

    public function __construct($name, ForgotOptionsInterface $forgotOptions)
    {
        $this->setForgotOptions($forgotOptions);
        parent::__construct($name);

        $this->add(array(
            'name' => 'newCredential',
            'options' => array(
                'label' => 'New Password',
            ),
            'attributes' => array(
                'type' => 'password',
            ),
        ));

        $this->add(array(
            'name' => 'newCredentialVerify',
            'options' => array(
                'label' => 'Verify New Password',
            ),
            'attributes' => array(
                'type' => 'password',
            ),
        ));

        $submitElement = new Element\Button('submit');
        $submitElement
            ->setLabel('Set new password')
            ->setAttributes(array(
                'type'  => 'submit',
            ));

        $this->add($submitElement, array(
            'priority' => -100,
        ));

    }

    public function setForgotOptions(ForgotOptionsInterface $forgotOptions)
    {
        $this->forgotOptions = $forgotOptions;
        return $this;
    }

    public function getForgotOptions()
    {
        return $this->forgotOptions;
    }
}

Set name as mandatory element for reset form creation


<?php

declare(strict_types=1);

namespace Cortex\Foundation\Http\Middleware;

use Closure;
use Illuminate\Support\Str;

class SetAuthDefaults
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($guard = $request->guard()) {
            // It's better to set auth defaults config globally,
            // instead of using `auth()->shouldUse($guard);`
            config()->set('auth.defaults.guard', $guard);
            config()->set('auth.defaults.provider', Str::plural($guard));
            config()->set('auth.defaults.passwords', $guard);
            config()->set('auth.defaults.emails', $guard);
        }

        return $next($request);
    }
}

<?php

declare(strict_types=1);

namespace Cortex\Foundation\Http\Middleware;

use Closure;
use Illuminate\Support\Str;

class SetAuthDefaults
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($guard = $request->guard()) {
            // It's better to set auth defaults config globally,
            // instead of using `auth()->shouldUse($guard);`
            config()->set('auth.defaults.guard', $guard);
            config()->set('auth.defaults.provider', Str::afterLast(Str::plural($guard), ':'));
            config()->set('auth.defaults.passwords', $guard);
            config()->set('auth.defaults.emails', $guard);
        }

        return $next($request);
    }
}

Fix setting `auth.defaults.provider` config option


<?php
/**
 * Slim Framework (https://slimframework.com)
 *
 * @link      https://github.com/slimphp/Slim
 * @copyright Copyright (c) 2011-2017 Josh Lockhart
 * @license   https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
 */
namespace Slim;

use Slim\Interfaces\RouteGroupInterface;

/**
 * A collector for Routable objects with a common middleware stack
 *
 * @package Slim
 */
class RouteGroup extends Routable implements RouteGroupInterface
{
    /**
     * Create a new RouteGroup
     *
     * @param string   $pattern  The pattern prefix for the group
     * @param callable $callable The group callable
     */
    public function __construct($pattern, $callable)
    {
        $this->pattern = $pattern;
        $this->callable = $callable;
    }

    /**
     * Invoke the group to register any Routable objects within it.
     *
     * @param App $app The App to bind the callable to.
     */
    public function __invoke(App $app)
    {
        // Resolve route callable
        $callable = $this->callable;
        if ($this->callableResolver) {
            $callable = $this->callableResolver->resolve($callable);
        }

        $callable($app);
    }
}

<?php
/**
 * Slim Framework (https://slimframework.com)
 *
 * @link      https://github.com/slimphp/Slim
 * @copyright Copyright (c) 2011-2017 Josh Lockhart
 * @license   https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License)
 */
namespace Slim;

use Slim\Interfaces\RouteGroupInterface;

/**
 * A collector for Routable objects with a common middleware stack
 *
 * @package Slim
 */
class RouteGroup extends Routable implements RouteGroupInterface
{
    /**
     * Create a new RouteGroup
     *
     * @param string   $pattern  The pattern prefix for the group
     * @param callable $callable The group callable
     */
    public function __construct($pattern, $callable)
    {
        $this->pattern = $pattern;
        $this->callable = $callable;
    }

    /**
     * Invoke the group to register any Routable objects within it.
     *
     * @param App $app The App to bind the callable to.
     */
    public function __invoke(App $app = null)
    {
        // Resolve route callable
        $callable = $this->callable;
        if ($this->callableResolver) {
            $callable = $this->callableResolver->resolve($callable);
        }

        $callable($app);
    }
}

Revert change, App must be nullable

Revert change, App must be nullable


<?php

namespace Sockets;

use React\Promise\When;

use React\Promise\Deferred;
use React\EventLoop\LoopInterface;
use Socket\Raw\Factory as RawFactory;
use \Exception;

class Factory
{
    private $loop;
    private $rawFactory;
    private $poller = null;

    public function __construct(LoopInterface $loop)
    {
        $this->loop = $loop;
        $this->rawFactory = new RawFactory();
    }

    public function createUdp4()
    {
        return new Datagram($this->rawFactory->createUdp4(), $this->getPoller());
    }

    public function createUdp6()
    {
        return new Datagram($this->rawFactory->createUdp6(), $this->getPoller());
    }

    public function createUdg()
    {
        return new Datagram($this->rawFactory->createUdg(), $this->getPoller());
    }

    /**
     *
     * @return SelectPoller
     */
    public function getPoller()
    {
        if ($this->poller === null) {
            $this->poller = new SelectPoller($this->loop);
        }
        return $this->poller;
    }
}

<?php

namespace Sockets;

use React\Promise\When;

use React\Promise\Deferred;
use React\EventLoop\LoopInterface;
use Socket\Raw\Factory as RawFactory;
use \Exception;

class Factory
{
    private $loop;
    private $rawFactory;
    private $poller = null;

    public function __construct(LoopInterface $loop)
    {
        $this->loop = $loop;
        $this->rawFactory = new RawFactory();
    }

    /**
     * create stream client socket connected to given address
     *
     * @param string $address
     * @return \Sockets\Stream
     * @throws Exception on error
     * @uses RawFactory::createClient()
     */
    public function createClient($address)
    {
        $socket = $this->rawFactory->createClient($address);
        if ($socket->getType() !== SOCK_STREAM) {
            $socket->close();
            throw new Exception('Not a stream address scheme');
        }
        return new Stream($socket, $this->getPoller());
    }

    /**
     * create stream server socket bound to and listening on the given address for incomming stream client connections
     *
     * @param string $address
     * @return \Sockets\Server
     * @throws Exception on error
     * @uses Server::listenAddress()
     */
    public function createServer($address)
    {
        $server = new Server($this->getPoller(), $this->rawFactory);
        $server->listenAddress($address);

        return $server;
    }

    public function createUdp4()
    {
        return new Datagram($this->rawFactory->createUdp4(), $this->getPoller());
    }

    public function createUdp6()
    {
        return new Datagram($this->rawFactory->createUdp6(), $this->getPoller());
    }

    public function createUdg()
    {
        return new Datagram($this->rawFactory->createUdg(), $this->getPoller());
    }

    /**
     *
     * @return SelectPoller
     */
    public function getPoller()
    {
        if ($this->poller === null) {
            $this->poller = new SelectPoller($this->loop);
        }
        return $this->poller;
    }
}

Add common createClient() and createServer() helpers


<?php

namespace j0k3r\FeedBundle\Controller;

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

/**
 * Feed controller.
 */
class FeedApiController extends Controller
{
    /**
     * Display some information about feeds, items, logs, etc ...
     *
     * @Template()
     *
     * @return array
     */
    public function indexAction($slug)
    {
        $dm   = $this->getDocumentManager();
        $feed = $dm->getRepository('j0k3rFeedBundle:Feed')->findOneBySlug($slug);

        if (!$feed) {
            throw $this->createNotFoundException('Feed does not exists.');
        }

        $feeditems = $dm->getRepository('j0k3rFeedBundle:FeedItem')->findByFeedId($feed->getId());

        return new Response($feed->render($feeditems));
    }

    /**
     * Returns the DocumentManager
     *
     * @return DocumentManager
     */
    private function getDocumentManager()
    {
        return $this->get('doctrine.odm.mongodb.document_manager');
    }
}

<?php

namespace j0k3r\FeedBundle\Controller;

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

/**
 * Feed controller.
 */
class FeedApiController extends Controller
{
    /**
     * Display some information about feeds, items, logs, etc ...
     *
     * @Template()
     *
     * @return array
     */
    public function indexAction($slug)
    {
        $dm   = $this->getDocumentManager();
        $feed = $dm->getRepository('j0k3rFeedBundle:Feed')->findOneBySlug($slug);

        if (!$feed) {
            throw $this->createNotFoundException('Feed does not exists.');
        }

        $feeditems = $dm->getRepository('j0k3rFeedBundle:FeedItem')->findByFeedId($feed->getId());

        return new Response(
            $feed->render($feeditems),
            200,
            array('Content-Type' => 'text/xml')
        );
    }

    /**
     * Returns the DocumentManager
     *
     * @return DocumentManager
     */
    private function getDocumentManager()
    {
        return $this->get('doctrine.odm.mongodb.document_manager');
    }
}

Send proper content-type for api

Send proper content-type for api


<?php namespace Modules\Blog\Repositories\Eloquent;

use Modules\Blog\Entities\Category;
use Modules\Blog\Repositories\CategoryRepository;
use Modules\Core\Repositories\Eloquent\EloquentBaseRepository;

class EloquentCategoryRepository extends EloquentBaseRepository implements CategoryRepository
{
    /**
     * Return all categories in the given language
     * @param $lang
     * @return mixed
     */
    public function allTranslatedIn($lang)
    {
        return $this->model->whereHas('translations', function($q) use($lang)
        {
            $q->where('locale', "$lang");
        })->get();
    }
}

<?php namespace Modules\Blog\Repositories\Eloquent;

use Modules\Blog\Entities\Category;
use Modules\Blog\Repositories\CategoryRepository;
use Modules\Core\Repositories\Eloquent\EloquentBaseRepository;

class EloquentCategoryRepository extends EloquentBaseRepository implements CategoryRepository
{
}

Remove unneeded method from concrete impl.


<?php

namespace Lexik\Bundle\JWTAuthenticationBundle\TokenExtractor;

use Symfony\Component\HttpFoundation\Request;

/**
 * AuthorizationHeaderTokenExtractor
 *
 * @author Nicolas Cabot <n.cabot@lexik.fr>
 */
class AuthorizationHeaderTokenExtractor implements TokenExtractorInterface
{
    /**
     * @var string
     */
    protected $prefix;

    /**
     * @var string
     */
    protected $name;

    /**
     * @param string $prefix
     * @param string $name
     */
    public function __construct($prefix, $name)
    {
        $this->prefix = $prefix;
        $this->name = $name;
    }

    /**
     * @param Request $request
     *
     * @return string
     */
    public function extract(Request $request)
    {
        if (!$request->headers->has($this->name)) {
            return false;
        }

        $headerParts = explode(' ', $request->headers->get($this->name));

        if (!(count($headerParts) === 2 && $headerParts[0] === $this->prefix)) {
            return false;
        }

        return $headerParts[1];
    }
}

<?php

namespace Lexik\Bundle\JWTAuthenticationBundle\TokenExtractor;

use Symfony\Component\HttpFoundation\Request;

/**
 * AuthorizationHeaderTokenExtractor
 *
 * @author Nicolas Cabot <n.cabot@lexik.fr>
 */
class AuthorizationHeaderTokenExtractor implements TokenExtractorInterface
{
    /**
     * @var string
     */
    protected $prefix;

    /**
     * @var string
     */
    protected $name;

    /**
     * @param string|null $prefix
     * @param string      $name
     */
    public function __construct($prefix, $name)
    {
        $this->prefix = $prefix;
        $this->name = $name;
    }

    /**
     * @param Request $request
     *
     * @return string
     */
    public function extract(Request $request)
    {
        if (!$request->headers->has($this->name)) {
            return false;
        }

        $authorizationHeader = $request->headers->get($this->name);

        if (empty($this->prefix)) {
            return $authorizationHeader;
        }

        $headerParts = explode(' ', $authorizationHeader);

        if (!(count($headerParts) === 2 && $headerParts[0] === $this->prefix)) {
            return false;
        }

        return $headerParts[1];
    }
}

Handle empty or null authorization header prefix


    header_color!='') ? ' style="background-color: '.e($snipeSettings->header_color).'"' : '' !!}>
        @if (($snipeSettings->show_images_in_email=='1' ) && ($snipeSettings::setupCompleted()))

            @if ($snipeSettings->brand == '3')
                @if ($snipeSettings->logo!='')
                    logo }}">
                @endif
                {{ $snipeSettings->site_name }}

            @elseif ($snipeSettings->brand == '2')
                @if ($snipeSettings->logo!='')
                    logo }}">
                @endif
            @else
                {{ $snipeSettings->site_name }}
            @endif
        @else
            Snipe-IT
        @endif

Use custom header color in emails

Use custom header color in emails


<?php

namespace Silktide\Reposition\QueryBuilder\QueryToken;

use Silktide\Reposition\Exception\QueryException;

class Value extends Token
{

    const TYPE_STRING = "string";
    const TYPE_INT = "int";
    const TYPE_FLOAT = "float";
    const TYPE_BOOL = "bool";
    const TYPE_NULL = "null";

    /**
     * @var mixed
     */
    protected $value;

    /**
     * @param string $type
     * @param mixed $value
     */
    public function __construct($type, $value)
    {
        $this->value = $value;
        $this->setType($type);
    }

    protected function setType($type)
    {
        switch ($type) {
            case self::TYPE_STRING:
            case self::TYPE_INT:
            case self::TYPE_FLOAT:
            case self::TYPE_BOOL:
            case self::TYPE_NULL:
                $this->type = $type;
                break;
            default:
                throw new QueryException("Invalid value type: '$type'");
        }
    }

    /**
     * @return mixed
     */
    public function getValue()
    {
        return $this->value;
    }

}

<?php

namespace Silktide\Reposition\QueryBuilder\QueryToken;

use Silktide\Reposition\Exception\QueryException;

class Value extends Token
{

    const TYPE_STRING = "string";
    const TYPE_INT = "int";
    const TYPE_FLOAT = "float";
    const TYPE_BOOL = "bool";
    const TYPE_NULL = "null";

    /**
     * @var mixed
     */
    protected $value;

    /**
     * @param string $type
     * @param mixed $value
     */
    public function __construct($type, $value)
    {
        $this->value = $value;
        $this->type = $type;
    }

    /**
     * @return mixed
     */
    public function getValue()
    {
        return $this->value;
    }

}

Remove the type constraints for the value token. References and tokens that don't represent a primitive value were breaking due to the unnecessary restrictions.


<?php

namespace WireMock\Client;

class JsonValueMatchingStrategy extends ValueMatchingStrategy
{
    const COMPARE_MODE__NON_EXTENSIBLE = "NON_EXTENSIBLE";
    const COMPARE_MODE__LENIENT = "LENIENT";

    private $_jsonCompareMode;

    function __construct($matchingValue, $jsonCompareMode)
    {
        parent::__construct('equalToJson', $matchingValue);
        $this->_jsonCompareMode = $jsonCompareMode;
    }

    function toArray()
    {
        $array = parent::toArray();
        $array['jsonCompareMode'] = $this->_jsonCompareMode;
        return $array;
    }
}

<?php

namespace WireMock\Client;

class JsonValueMatchingStrategy extends ValueMatchingStrategy
{
    const COMPARE_MODE__NON_EXTENSIBLE = "NON_EXTENSIBLE";
    const COMPARE_MODE__LENIENT = "LENIENT";
    const COMPARE_MODE__STRICT = "STRICT";
    const COMPARE_MODE__STRICT_ORDER = "STRICT_ORDER";

    private $_jsonCompareMode;

    function __construct($matchingValue, $jsonCompareMode)
    {
        parent::__construct('equalToJson', $matchingValue);
        $this->_jsonCompareMode = $jsonCompareMode;
    }

    function toArray()
    {
        $array = parent::toArray();
        $array['jsonCompareMode'] = $this->_jsonCompareMode;
        return $array;
    }
}

Add strict & strict order JSON compare modes


<?php
require __DIR__.'/../../../vendor/autoload.php';
require __DIR__.'/../../Init/init.php';

use JiraRestlib\Api\Api;
use JiraRestlib\Config\Config;
use JiraRestlib\Resources\Attachments\Attachments;

$defaultOption = array("auth"      => array(USERNAME, PASSWORD),
                       "verify"    => SSL_VERIFICATION);

$config = new Config(JIRA_HOST);
$config->setSSLVerification(SSL_VERIFICATION);
$config->setJiraAuth(USERNAME, PASSWORD);

$api = new Api($config);
$attachmentResource = new Attachments();

//use an appropriate issue name or id
$issueKey = "JIR-2";

//valid filenames with path
$files = array("files/jira.jpg",
               "files/a.pdf",);

$attachmentResource->addAttachment($issueKey, $files);

$result = $api->getRequestResult($attachmentResource);

$resultObject = $result->getResponse();
$resultHeader = $result->getResponseHeaders();
$resultStatus = $result->getResponseHttpStatusCode();

print_r($resultObject);

echo PHP_EOL;
print_r("Status:".$resultStatus);

echo PHP_EOL;
print_r("Has error:".$result->hasError());
echo PHP_EOL;

if($result->hasError())
{
    print_r($result->getErrorMessages());
    print_r($result->getErrors());
}

echo PHP_EOL;
echo "END";
echo PHP_EOL;

echo "END";

<?php
require __DIR__.'/../../../vendor/autoload.php';
require __DIR__.'/../../Init/init.php';

use JiraRestlib\Api\Api;
use JiraRestlib\Config\Config;
use JiraRestlib\Resources\Attachments\Attachments;

$config = new Config(JIRA_HOST);
$config->setSSLVerification(SSL_VERIFICATION);
$config->setJiraAuth(USERNAME, PASSWORD);

$api = new Api($config);
$attachmentResource = new Attachments();

//use an appropriate issue name or id
$issueKey = "JIR-2";

//valid filenames with path
$files = array("files/jira.jpg",
               "files/a.pdf",);

$attachmentResource->addAttachment($issueKey, $files);

$result = $api->getRequestResult($attachmentResource);

$resultObject = $result->getResponse();
$resultHeader = $result->getResponseHeaders();
$resultStatus = $result->getResponseHttpStatusCode();

print_r($resultObject);

echo PHP_EOL;
print_r("Status:".$resultStatus);

echo PHP_EOL;
print_r("Has error:".$result->hasError());
echo PHP_EOL;

if($result->hasError())
{
    print_r($result->getErrorMessages());
    print_r($result->getErrors());
}

echo PHP_EOL;
echo "END";
echo PHP_EOL;

echo "END";

Remove unnecessary part from attachment example


<?php

namespace Nathiss\Bundle\QuoteGeneratorBundle\Repository;

/**
 * QuoteRepository
 */
class QuoteRepository extends \Doctrine\ORM\EntityRepository
{
    /**
     * Selects Query from DB randomly
     *
     * @return \Nathiss\Bundle\QuoteGenerateBundle\Entity\Quote
     */
    public function findOneRandomly()
    {
        $count = $this->createQueryBuilder('q')
            ->select('COUNT(q)')
            ->getQuery()
            ->getSingleScalarResult();

        return $this->createQueryBuilder('q')
            ->setFirstResult(rand(0, $count-1))
            ->setMaxResults(1)
            ->getQuery()
            ->getSingleResult();
    }
}

<?php

namespace Nathiss\Bundle\QuoteGeneratorBundle\Repository;

/**
 * QuoteRepository
 */
class QuoteRepository extends \Doctrine\ORM\EntityRepository
{
    /**
     * Selects Quote from DB randomly
     *
     * @return \Nathiss\Bundle\QuoteGenerateBundle\Entity\Quote
     */
    public function findOneRandomly()
    {
        $count = $this->createQueryBuilder('q')
            ->select('COUNT(q)')
            ->getQuery()
            ->getSingleScalarResult();

        return $this->createQueryBuilder('q')
            ->setFirstResult(rand(0, $count-1))
            ->setMaxResults(1)
            ->getQuery()
            ->getSingleResult();
    }
}

Fix tiny typo in comment

Fix tiny typo in comment


<?php
/**
 * This file is Copyright (c).
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Component\Authentication;

use Doctrine\ORM\EntityManager;

use Component\Entity\User;
use Component\Response\JsonResponse;

class Authentication
{
    private $entityManager;

    function __construct(EntityManager $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    /**
     * @param string $username
     * @param string $password
     * @param string $token
     * @return JsonResponse
     */
    public function verify($username, $password, $token)
    {
        if (empty($username) || empty($password)) {
            return new JsonResponse("Insufficient argument", JsonResponse::BAD_REQUEST);
        }

        try {
            $userRepo = $this->entityManager->getRepository(User::getClassName());
            if (empty($userRepo)) {
                return new JsonResponse("Invalid entity supplied.", JsonResponse::BAD_REQUEST);
            }

            $found = $userRepo->findOneBy(array("username" => $username));
            if (!$found || password_verify($password, $found->getPassword())) {
                return new JsonResponse("Invalid username or password.", JsonResponse::BAD_REQUEST);
            }

            return new JsonResponse("verified", JsonResponse::OK, array(), array("token" => $token));
        } catch (\Exception $e) {
            return new JsonResponse($e->getMessage(), JsonResponse::INTERNAL_SERVER_ERROR);
        }
    }
}

<?php
/**
 * This file is Copyright (c).
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Component\Authentication;

use Doctrine\ORM\EntityManager;

use Component\Entity\User;
use Component\Response\JsonResponse;

class Authentication
{
    private $entityManager;

    function __construct(EntityManager $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    /**
     * @param string $username
     * @param string $password
     * @param string $token
     * @return JsonResponse
     */
    public function verify($username, $password, $token)
    {
        $tokenNode = array();
        if (!empty($token)) {
            $tokenNode["token"] = $token;
        }

        if (empty($username) || empty($password)) {
            return new JsonResponse("Insufficient argument", JsonResponse::BAD_REQUEST, array(), $tokenNode);
        }

        try {
            $userRepo = $this->entityManager->getRepository(User::getClassName());
            if (empty($userRepo)) {
                return new JsonResponse("Invalid entity supplied.", JsonResponse::BAD_REQUEST, array(), $tokenNode);
            }

            $found = $userRepo->findOneBy(array("username" => $username));
            if (!$found || !password_verify($password, $found->getPassword())) {
                return new JsonResponse("Invalid username or password.", JsonResponse::BAD_REQUEST, array(), $tokenNode);
            }

            return new JsonResponse("verified", JsonResponse::OK, array(), $tokenNode);
        } catch (\Exception $e) {
            return new JsonResponse($e->getMessage(), JsonResponse::INTERNAL_SERVER_ERROR);
        }
    }
}

Fix bugs -- token is added into response json only when authentication succeeded and invalid username and password always show up even though username and password are correct


<?php
namespace EventDispatcher\EventManager;

use Zend\EventManager\EventManagerInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Mvc\MvcEvent;

class Dispatcher
{
    protected $config = array();
    protected $sm;

    public function __construct(array $config, ServiceLocatorInterface $sm)
    {
        $this->config = $config;
        $this->sm = $sm;
    }

    public function attachListeners(EventManagerInterface $eventManager)
    {
        $events = array(
            'bootstrap', 'dispatch', 'dispatch.error', 'finish', 'render', 'render.error', 'route'
        );

        foreach ($events as $event) {
            if (isset($this->config($event)) && count($this->config[$event]) > 0) {
                $this->attachFor($eventManager, $event);
            }
        }
    }

    protected function attachFor(EventManagerInterface $eventManager, $eventName)
    {
        foreach ($this->config[$eventName] as $serviceName => $priority) {
            if (is_numeric($serviceName)) {
                // not an associative array
                $serviceName = $priority;
                $priority = 1;
            }

            $sm = $this->sm;
            $eventManager->attach($eventName, function ($event) use ($sm, $serviceName) {
                $listener = $sm->get($serviceName);
                return $listener->onEvent($event);
            }, $priority);
        }
    }
}

<?php
namespace EventDispatcher\EventManager;

use Zend\EventManager\EventManagerInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\Mvc\MvcEvent;

class Dispatcher
{
    protected $config = array();
    protected $sm;

    public function __construct(array $config, ServiceLocatorInterface $sm)
    {
        $this->config = $config;
        $this->sm = $sm;
    }

    public function attachListeners(EventManagerInterface $eventManager)
    {
        $events = array(
            'bootstrap', 'dispatch', 'dispatch.error', 'finish', 'render', 'render.error', 'route'
        );

        foreach ($events as $event) {
            if (isset($this->config[$event]) && count($this->config[$event]) > 0) {
                $this->attachFor($eventManager, $event);
            }
        }
    }

    protected function attachFor(EventManagerInterface $eventManager, $eventName)
    {
        foreach ($this->config[$eventName] as $serviceName => $priority) {
            if (is_numeric($serviceName)) {
                // not an associative array
                $serviceName = $priority;
                $priority = 1;
            }

            $sm = $this->sm;
            $eventManager->attach($eventName, function ($event) use ($sm, $serviceName) {
                $listener = $sm->get($serviceName);
                return $listener->onEvent($event);
            }, $priority);
        }
    }
}

Fix typo in array access

Fix typo in array access


<?php
namespace PharIo\Phive\Cli;

class ConsoleInput implements Input {

    /**
     * @var Cli\Output
     */
    private $output;

    /**
     * ConsoleInput constructor.
     *
     * @param Cli\Output $output
     */
    public function __construct(Output $output) {
        $this->output = $output;
    }

    /**
     * @param string $message
     *
     * @return bool
     */
    public function confirm($message) {
        $this->output->writeText(rtrim($message) . ' [Y|n] ');
        $response = fgetc(STDIN);
        return (trim($response) === '' || strpos('Yy', $response[0]) !== false);
    }
}

<?php
namespace PharIo\Phive\Cli;

class ConsoleInput implements Input {

    /**
     * @var Output
     */
    private $output;

    /**
     * ConsoleInput constructor.
     *
     * @param Output $output
     */
    public function __construct(Output $output) {
        $this->output = $output;
    }

    /**
     * @param string $message
     *
     * @return bool
     */
    public function confirm($message) {
        do {
            $this->output->writeText(rtrim($message) . ' [Y|n] ');
            $response = strtolower(rtrim(fgets(STDIN)));
        } while (!in_array($response, ['y','n']));

        return ($response === 'y');
    }
}

Fix user input handling for confirm()

Fix user input handling for confirm()


<?php

/**
 * This file is part of Ibuildings QA-Tools.
 *
 * (c) Ibuildings
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Ibuildings\QA\Tools\Common\Console\Helper;

use Symfony\Component\Console\Helper\DialogHelper as BaseDialogHelper;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class DialogHelper
 *
 * @package Ibuildings\QA\Tools\Common\Console\Helper
 */
class DialogHelper extends BaseDialogHelper
{
    /**
     * Asks a confirmation to the user.
     *
     * The question will be asked until the user answers by nothing, yes, or no.
     *
     * @param OutputInterface $output   An Output instance
     * @param string|array    $question The question to ask
     * @param Boolean         $default  The default answer if the user enters nothing
     *
     * @return Boolean true if the user has confirmed, false otherwise
     */
    public function askConfirmation(OutputInterface $output, $question, $default = true)
    {
        $hint = ($default) ? '[Y/n] ' : '[y/N] ';
        $question = $question . ' ' . $hint;

        return parent::askConfirmation($output, $question, $default);
    }
}

<?php

/**
 * This file is part of Ibuildings QA-Tools.
 *
 * (c) Ibuildings
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Ibuildings\QA\Tools\Common\Console\Helper;

use Symfony\Component\Console\Helper\DialogHelper as BaseDialogHelper;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class DialogHelper
 *
 * @package Ibuildings\QA\Tools\Common\Console\Helper
 */
class DialogHelper extends BaseDialogHelper
{
    /**
     * Asks a confirmation to the user.
     *
     * The question will be asked until the user answers by nothing, yes, or no.
     *
     * @param OutputInterface $output   An Output instance
     * @param string|array    $question The question to ask
     * @param Boolean         $default  The default answer if the user enters nothing
     *
     * @return Boolean true if the user has confirmed, false otherwise
     */
    public function askConfirmation(OutputInterface $output, $question, $default = true)
    {
        $hint = ($default) ? ' [Y/n] ' : ' [y/N] ';

        if (is_string($question)) {
            $question = $question . $hint;
        } else {
            array_push($question, array_pop($question) . $hint);
        }

        return parent::askConfirmation($output, $question, $default);
    }
}

Handle both strings and arrays, as the parent does