<?php

namespace Kunstmaan\NodeBundle\Event;

use Kunstmaan\AdminBundle\Event\BcEvent;

final class SlugSecurityEvent extends BcEvent
{
    private $node;

    private $nodeTranslation;

    private $entity;

    private $request;

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

    /**
     * @param mixed $node
     */
    public function setNode($node)
    {
        $this->node = $node;

        return $this;
    }

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

    /**
     * @param mixed $nodeTranslation
     */
    public function setNodeTranslation($nodeTranslation)
    {
        $this->nodeTranslation = $nodeTranslation;

        return $this;
    }

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

    /**
     * @param mixed $entity
     */
    public function setEntity($entity)
    {
        $this->entity = $entity;

        return $this;
    }

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

    /**
     * @param mixed $request
     */
    public function setRequest($request)
    {
        $this->request = $request;

        return $this;
    }
}

<?php

namespace Kunstmaan\NodeBundle\Event;

use Kunstmaan\AdminBundle\Event\BcEvent;
use Kunstmaan\NodeBundle\Entity\HasNodeInterface;
use Kunstmaan\NodeBundle\Entity\Node;
use Kunstmaan\NodeBundle\Entity\NodeTranslation;
use Symfony\Component\HttpFoundation\Request;

final class SlugSecurityEvent extends BcEvent
{
    /** @var Node|null */
    private $node;
    /** @var NodeTranslation|null */
    private $nodeTranslation;
    /** @var HasNodeInterface|null */
    private $entity;
    /** @var Request|null */
    private $request;

    /**
     * @return Node|null
     */
    public function getNode()
    {
        return $this->node;
    }

    /**
     * @param Node $node
     */
    public function setNode($node)
    {
        $this->node = $node;

        return $this;
    }

    /**
     * @return NodeTranslation|null
     */
    public function getNodeTranslation()
    {
        return $this->nodeTranslation;
    }

    /**
     * @param NodeTranslation $nodeTranslation
     */
    public function setNodeTranslation($nodeTranslation)
    {
        $this->nodeTranslation = $nodeTranslation;

        return $this;
    }

    /**
     * @return HasNodeInterface|null
     */
    public function getEntity()
    {
        return $this->entity;
    }

    /**
     * @param HasNodeInterface $entity
     */
    public function setEntity($entity)
    {
        $this->entity = $entity;

        return $this;
    }

    /**
     * @return Request|null
     */
    public function getRequest()
    {
        return $this->request;
    }

    /**
     * @param Request $request
     */
    public function setRequest($request)
    {
        $this->request = $request;

        return $this;
    }
}

[NodeBundle] Set correct typehints on methods and properties


<?php

declare(strict_types=1);

/**
 * Copyright (c) 2013-2017 OpenCFP
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 *
 * @see https://github.com/opencfp/opencfp
 */

namespace OpenCFP\Http\Controller;

use OpenCFP\Domain\Model\Talk;
use Symfony\Component\HttpFoundation\Response;

class PagesController extends BaseController
{
    public function showHomepage(): Response
    {
        return $this->render('home.twig', $this->getContextWithTalksCount());
    }

    public function showSpeakerPackage(): Response
    {
        return $this->render('package.twig', $this->getContextWithTalksCount());
    }

    public function showTalkIdeas(): Response
    {
        return $this->render('ideas.twig', $this->getContextWithTalksCount());
    }

    private function getContextWithTalksCount()
    {
        return ['number_of_talks' => Talk::count()];
    }
}

<?php

declare(strict_types=1);

/**
 * Copyright (c) 2013-2017 OpenCFP
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 *
 * @see https://github.com/opencfp/opencfp
 */

namespace OpenCFP\Http\Controller;

use OpenCFP\Domain\Model\Talk;
use Symfony\Component\HttpFoundation\Response;

class PagesController extends BaseController
{
    public function showHomepage(): Response
    {
        return $this->render('home.twig', [
            'number_of_talks' => Talk::count(),
        ]);
    }

    public function showSpeakerPackage(): Response
    {
        return $this->render('package.twig');
    }

    public function showTalkIdeas(): Response
    {
        return $this->render('ideas.twig');
    }
}

Remove number of talks variable from pages that dont use it.

The speaker package and the talk ideas pages didn't use the
number_of_talks variable, so it had no sense to give it to them.
Since it is now only used in one place it makes more sense to inline it


<?php

return [
    /**
     * User class used for ACL.
     */
    'user'       => App\User::class,

    /**
     * Role class used for ACL.
     */
    'role'       => Yajra\Acl\Models\Role::class,

    /**
     * Permission class used for ACL.
     */
    'permission' => Yajra\Acl\Models\Permission::class,

    /**
     * Cache config.
     */
    'cache'      => [
        'enabled' => true,

        'key' => 'permissions.policies',
    ],
];

<?php

return [
    /**
     * User class used for ACL.
     */
    'user'       => App\Models\User::class,

    /**
     * Role class used for ACL.
     */
    'role'       => Yajra\Acl\Models\Role::class,

    /**
     * Permission class used for ACL.
     */
    'permission' => Yajra\Acl\Models\Permission::class,

    /**
     * Cache config.
     */
    'cache'      => [
        'enabled' => true,

        'key' => 'permissions.policies',
    ],
];

Use new default user models path.

Use new default user models path.


<?php

namespace Tests;

use \Mockery as m;
use Rosio\EncryptedCookie\EncryptedCookie;
use Rosio\EncryptedCookie\CookieStorage;
use Rosio\EncryptedCookie\CryptoSystem\MOCK_MOCK;

class EncryptedCookieTest extends \PHPUnit_Framework_TestCase
{
	private $cookie;

	public function setUp ()
	{
		$this->createCookie();
	}

	public function tearDown ()
	{
		m::close();
	}

	protected function createCookie ($name = 'test')
	{
		$this->cookie = new EncryptedCookie($name);
		$this->cookie->setCryptoSystem(new MOCK_MOCK);
	}

	public function testGettersSetters ()
	{
		$this->assertEquals($this->cookie->getName(), 'test');

		$this->cookie->setData('test');
		$this->assertEquals($this->cookie->getData(), 'test');

		$time = time() * 60 * 60 * 24; // 24 hours
		$this->cookie->setExpiration($time);
		$this->assertEquals($this->cookie->getExpiration(), $time);

		$this->cookie->setDomain('google.com');
		$this->assertEquals($this->cookie->getDomain(), 'google.com');

		$this->cookie->setPath('/test/');
		$this->assertEquals($this->cookie->getPath(), '/test/');

		$this->cookie->setSecure(true);
		$this->assertTrue($this->cookie->isSecure());

		$this->cookie->setHttpOnly(true);
		$this->assertTrue($this->cookie->isHttpOnly());
	}
}

<?php

namespace Tests;

use \Mockery as m;
use Rosio\EncryptedCookie\Cookie;
use Rosio\EncryptedCookie\CookieStorage;
use Rosio\EncryptedCookie\CryptoSystem\MOCK_MOCK;

class EncryptedCookieTest extends \PHPUnit_Framework_TestCase
{
	private $cookie;

	public function setUp ()
	{
		$this->createCookie();
	}

	public function tearDown ()
	{
		m::close();
	}

	protected function createCookie ($name = 'test')
	{
		$this->cookie = new Cookie($name);
	}

	public function testGettersSetters ()
	{
		$this->assertEquals($this->cookie->getName(), 'test');

		$this->cookie->setData('test');
		$this->assertEquals($this->cookie->getData(), 'test');

		$time = time() * 60 * 60 * 24; // 24 hours
		$this->cookie->setExpiration($time);
		$this->assertEquals($this->cookie->getExpiration(), $time);

		$this->cookie->setDomain('google.com');
		$this->assertEquals($this->cookie->getDomain(), 'google.com');

		$this->cookie->setPath('/test/');
		$this->assertEquals($this->cookie->getPath(), '/test/');

		$this->cookie->setSecure(true);
		$this->assertTrue($this->cookie->isSecure());

		$this->cookie->setHttpOnly(true);
		$this->assertTrue($this->cookie->isHttpOnly());
	}
}

Modify cookie test to work with new cookies


<?php

/**
*       This custom class must be placed in the folder /AlloPass/Hipay/Helper
*       You have to personalize  the method getCustomData and return an json of your choice.
*
*/
class Allopass_Hipay_Helper_CustomData extends Mage_Core_Helper_Abstract
{
    /**
	 *  Return yours customs datas in a json for gateway transaction request
     *
     * @param array $payment
	 * @param float $amount
	 *
     */
    public function getCustomData($payment,$amount)
    {
        $customData = array();

        // An example of adding custom data
        if ($payment)
        {
            $customData['my_field_custom_1'] = $payment->getOrder()->getBaseCurrencyCode();
        }

        return json_encode($customData);
    }
}

<?php

/**
*       This custom class must be placed in the folder /AlloPass/Hipay/Helper
*       You have to personalize  the method getCustomData and return an json of your choice.
*
*/
class Allopass_Hipay_Helper_CustomData extends Mage_Core_Helper_Abstract
{
    /**
	 *  Return yours customs datas in a json for gateway transaction request
     *
     * @param array $payment
	 * @param float $amount
	 *
     */
    public function getCustomData($payment,$amount)
    {
        $customData = array();

        // An example of adding custom data
        if ($payment)
        {
            $customData['my_field_custom_1'] = $payment->getOrder()->getBaseCurrencyCode();
        }

        return $customData;
    }
}

Add support of custom data

Add support of custom data


<?php
declare(strict_types=1);

namespace WoohooLabs\Yin\JsonApi\Exception;

use WoohooLabs\Yin\JsonApi\Schema\Error\Error;

class RelationshipNotExists extends AbstractJsonApiException
{
    /**
     * @var string
     */
    protected $relationship;

    public function __construct(string $relationship)
    {
        parent::__construct("The requested relationship '$relationship' does not exist!");
        $this->relationship = $relationship;
    }

    protected function getErrors(): array
    {
        return [
            Error::create()
                ->setStatus("404")
                ->setCode("RELATIONSHIP_NOT_EXISTS")
                ->setTitle("The requested relationship '$this->relationship' does not exist!")
                ->setDetail($this->getMessage())
        ];
    }

    public function getRelationship(): string
    {
        return $this->relationship;
    }
}

<?php
declare(strict_types=1);

namespace WoohooLabs\Yin\JsonApi\Exception;

use WoohooLabs\Yin\JsonApi\Schema\Error\Error;

class RelationshipNotExists extends AbstractJsonApiException
{
    /**
     * @var string
     */
    protected $relationship;

    public function __construct(string $relationship)
    {
        parent::__construct("The requested relationship '$relationship' does not exist!");
        $this->relationship = $relationship;
    }

    protected function getErrors(): array
    {
        return [
            Error::create()
                ->setStatus("404")
                ->setCode("RELATIONSHIP_NOT_EXISTS")
                ->setTitle("The requested relationship does not exist!")
                ->setDetail($this->getMessage())
        ];
    }

    public function getRelationship(): string
    {
        return $this->relationship;
    }
}

Fix spec compliance of error title

Fix spec compliance of error title


@if($widget->show_title)

param('header_class'))class="{{$widget->param('header_class')}}"@endif>{{$widget->title}}

@endif

param('menu_class', 'nav navbar-nav')}}">
    @include('system.menu.bootstrap', ['menu' => $$menu])

Add widget title on plain template.

Add widget title on plain template.


<?php

declare(strict_types=1);

namespace DI\Definition\Resolver;

use DI\Definition\Definition;
use DI\Definition\InstanceDefinition;
use DI\DependencyException;
use Psr\Container\NotFoundExceptionInterface;

/**
 * Injects dependencies on an existing instance.
 *
 * @since 5.0
 * @author Matthieu Napoli <matthieu@mnapoli.fr>
 */
class InstanceInjector extends ObjectCreator
{
    /**
     * Injects dependencies on an existing instance.
     *
     * @param InstanceDefinition $definition
     */
    public function resolve(Definition $definition, array $parameters = [])
    {
        try {
            $this->injectMethodsAndProperties($definition->getInstance(), $definition->getObjectDefinition());
        } catch (NotFoundExceptionInterface $e) {
            $message = sprintf(
                'Error while injecting dependencies into %s: %s',
                get_class($definition->getInstance()),
                $e->getMessage()
            );

            throw new DependencyException($message, 0, $e);
        }
    }

    public function isResolvable(Definition $definition, array $parameters = []) : bool
    {
        return true;
    }
}

<?php

declare(strict_types=1);

namespace DI\Definition\Resolver;

use DI\Definition\Definition;
use DI\Definition\InstanceDefinition;
use DI\DependencyException;
use Psr\Container\NotFoundExceptionInterface;

/**
 * Injects dependencies on an existing instance.
 *
 * @since 5.0
 * @author Matthieu Napoli <matthieu@mnapoli.fr>
 */
class InstanceInjector extends ObjectCreator
{
    /**
     * Injects dependencies on an existing instance.
     *
     * @param InstanceDefinition $definition
     */
    public function resolve(Definition $definition, array $parameters = [])
    {
        try {
            $this->injectMethodsAndProperties($definition->getInstance(), $definition->getObjectDefinition());
        } catch (NotFoundExceptionInterface $e) {
            $message = sprintf(
                'Error while injecting dependencies into %s: %s',
                get_class($definition->getInstance()),
                $e->getMessage()
            );

            throw new DependencyException($message, 0, $e);
        }

        return $definition;
    }

    public function isResolvable(Definition $definition, array $parameters = []) : bool
    {
        return true;
    }
}

Fix missing return (phpstan error)

Fix missing return (phpstan error)


<?php

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

namespace Sylius\Component\Grid\Sorting;

use Sylius\Component\Grid\Data\DataSourceInterface;
use Sylius\Component\Grid\Definition\Field;
use Sylius\Component\Grid\Definition\Grid;
use Sylius\Component\Grid\Parameters;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
final class Sorter implements SorterInterface
{
    /**
     * {@inheritdoc}
     */
    public function sort(DataSourceInterface $dataSource, Grid $grid, Parameters $parameters)
    {
        $expressionBuilder = $dataSource->getExpressionBuilder();

        $sorting = $parameters->get('sorting', $grid->getSorting());

        foreach ($sorting as $field => $order) {
            $gridField = $grid->getField($field);
            $property = $gridField->getSortable();

            $expressionBuilder->addOrderBy($property, $order);
        }
    }
}

<?php

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

namespace Sylius\Component\Grid\Sorting;

use Sylius\Component\Grid\Data\DataSourceInterface;
use Sylius\Component\Grid\Definition\Grid;
use Sylius\Component\Grid\Parameters;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
final class Sorter implements SorterInterface
{
    /**
     * {@inheritdoc}
     */
    public function sort(DataSourceInterface $dataSource, Grid $grid, Parameters $parameters)
    {
        $expressionBuilder = $dataSource->getExpressionBuilder();

        $sorting = $parameters->get('sorting', $grid->getSorting());

        foreach ($sorting as $field => $order) {
            $gridField = $grid->getField($field);
            $property = $gridField->getSortable();

            if (null !== $property) {
                $expressionBuilder->addOrderBy($property, $order);
            }
        }
    }
}

Fix sorter for fields with null sortable property


<?php
/**
 * Plugin Name: Simple Random Image
 * Plugin URI: https://github.com/mitogh/Simple-Random-Image
 * Description: Generate a random image from the attachements file.
 * Version: 0.1
 * Author: Crisoforo.
 * Author URI: http://www.crisoforo.com
 * License: MIT
 */
include_once(plugin_dir_path(__FILE__).'/class-simple-random-image.php');
include_once(plugin_dir_path(__FILE__).'/simple-random-image-shortcodes.php');

add_action('admin_menu', 'simple_random_image');

function simple_random_image() {
    add_menu_page(__('Simple Random Image','Simple Random Image'), __('Simple Random Image','simple_random_image'), 'manage_options', 'simple-random-image', 'simple_random_image_options' );
}

function simple_random_image_options(){
    if( !current_user_can('manage_options') ){
        wp_die(__('You do not have sufficient permission to access this page'));
    }
?>

Simple Random Image

<?php
}// Options

<?php
/**
 * Plugin Name: Simple Random Image
 * Plugin URI: https://github.com/mitogh/Simple-Random-Image
 * Description: Generate a random image from the attachements file.
 * Version: 0.1
 * Author: Crisoforo.
 * Author URI: http://www.crisoforo.com
 * License: Apache 2.0
 */
include_once(plugin_dir_path(__FILE__).'/class-simple-random-image.php');
include_once(plugin_dir_path(__FILE__).'/simple-random-image-shortcodes.php');

add_action('admin_menu', 'simple_random_image');

function simple_random_image() {
    add_menu_page(__('Simple Random Image','Simple Random Image'), __('Simple Random Image','simple_random_image'), 'manage_options', 'simple-random-image', 'simple_random_image_options' );
}

function simple_random_image_options(){
    if( !current_user_can('manage_options') ){
        wp_die(__('You do not have sufficient permission to access this page'));
    }
?>

Simple Random Image

<?php
}// Options

Update the LICENCE on the main file of the plugin


<?php

date_default_timezone_set('Europe/London');

require_once 'config.inc.php';
require_once 'MailManager.php';

try
{
  $mm = new MailManager($database_host, $database_user, $database_pass, $database_name);
  $mm->addRecipient('test@example.org');
}
catch (Exception $e)
{
  print $e->getMessage() . "\n";
}

try
{
  $mm = new MailManager($database_host, $database_user, $database_pass, $database_name);
  $mm->addRecipient('doesnotexist@manchester.ac.uk');
  $mm->addRecipient('doesnotexist@manchester.ac.uk');
  $mm->addRecipient('doesnotexist@manchester.ac.uk');
  $mm->addRecipient('doesnotexist@manchester.ac.uk');
  $mm->addRecipient('doesnotexist@manchester.ac.uk');
  $mm->addRecipient('doesnotexist@manchester.ac.uk');
  $mm->addRecipient('doesnotexist@manchester.ac.uk');

  $mm->send();
}
catch (Exception $e)
{
  print $e->getMessage() . "\n";
}

<?php

date_default_timezone_set('Europe/London');

require_once 'config.inc.php';
require_once 'MailManager.php';

// Recipient not in list of permitted domains
try
{
  $mm = new MailManager($database_host, $database_user, $database_pass, $database_name);
  $mm->addRecipient('test@example.org');
}
catch (Exception $e)
{
  print $e->getMessage() . "\n";
}

// Too many recipients
try
{
  $mm = new MailManager($database_host, $database_user, $database_pass, $database_name);

  $mm->setSubject('Test');
  $mm->setBody('Body');

  $mm->addRecipient('doesnotexist@manchester.ac.uk');
  $mm->addRecipient('doesnotexist@manchester.ac.uk');
  $mm->addRecipient('doesnotexist@manchester.ac.uk');
  $mm->addRecipient('doesnotexist@manchester.ac.uk');
  $mm->addRecipient('doesnotexist@manchester.ac.uk');
  $mm->addRecipient('doesnotexist@manchester.ac.uk');
  $mm->addRecipient('doesnotexist@manchester.ac.uk');

  $mm->send();
}
catch (Exception $e)
{
  print $e->getMessage() . "\n";
}

Set subject and body in 'too many recipients' test

Subject and body are tested first, so if they are not set the 'too many
recipients' exception will never be triggered.


<?php

// search-form same behavior as genesis with additional classes
// for bootstrap styling

add_filter( 'genesis_search_form', 'bsg_search_form', 10, 4);

function bsg_search_form( $form, $search_text, $button_text, $label ) {

    $value_or_placeholder = ( get_search_query() == '' ) ? 'placeholder' : 'value';

    $form = sprintf( '<form method="get" class="search-form" action="%s" role="search">%s<input type="search" class="search-query" name="s" %s="%s" /> <input type="submit" class="btn" value="%s" /></form>', home_url( '/' ), esc_html( $label ), $value_or_placeholder, esc_attr( $search_text ), esc_attr( $button_text ) );

    return $form;
}

<?php

// search-form same behavior as genesis with additional classes
// for bootstrap styling

add_filter( 'genesis_search_form', 'bsg_search_form', 10, 4);

function bsg_search_form( $form, $search_text, $button_text, $label ) {

    $value_or_placeholder = ( get_search_query() == '' ) ? 'placeholder' : 'value';

$format = <<<EOT
<form method="get" class="search-form form-inline" action="%s" role="search">

        %s

            <input type="search" class="search-field form-control" id="bsg-search-form" name="s" %s="%s">

                <button type="submit" class="search-submit btn btn-default">

                    %s
                </button>

</form>
EOT;

    return sprintf( $format, home_url( '/' ), esc_html( $label ), $value_or_placeholder, esc_attr( $search_text ), esc_attr( $button_text ) );
}

Improve search form rendering by using Bootstrap

Fixes #57


<?php

namespace App\Middleware;

use Slim\Http\Request;
use Slim\Http\Response;

class Cors implements MiddlewareInterface
{
    /**
     * @var array
     */
    protected $options;

    /**
     * Constructor.
     *
     * @param array $options
     */
    public function __construct(array $options)
    {
        $this->options = $options;
    }

    /**
     * {@inheritdoc}
     */
    public function __invoke(Request $request, Response $response, callable $next)
    {
        $response = $response
            ->withHeader('Access-Control-Allow-Origin', $this->options['origin'])
            ->withHeader('Access-Control-Allow-Headers', $this->options['allow_headers'])
            ->withHeader('Access-Control-Expose-Headers', $this->options['expose_headers'])
            ->withHeader('Access-Control-Allow-Methods', $this->options['methods'])
            ->withHeader('Access-Control-Max-Age', $this->options['max_age']);

        return $next($request, $response);
    }
}

<?php

namespace App\Middleware;

use Slim\Http\Request;
use Slim\Http\Response;

class Cors implements MiddlewareInterface
{
    /**
     * @var array
     */
    protected $options;

    /**
     * Constructor.
     *
     * @param array $options
     */
    public function __construct(array $options)
    {
        $this->options = $options;
    }

    /**
     * {@inheritdoc}
     */
    public function __invoke(Request $request, Response $response, callable $next)
    {
        $headers = [
            'origin'         => 'Access-Control-Allow-Origin',
            'methods'        => 'Access-Control-Allow-Methods',
            'allow_headers'  => 'Access-Control-Allow-Headers',
            'expose_headers' => 'Access-Control-Expose-Headers',
            'max_age'        => 'Access-Control-Max-Age',
        ];

        foreach ($headers as $key => $name) {
            if (isset($this->options[$key])) {
                $response = $response->withHeader($name, $this->options[$key]);
            }
        }

        return $next($request, $response);
    }
}

Allow removing CORS headers without editing the middleware class


<?php

namespace RulerZ\Target\DoctrineORM;

use Hoa\Ruler\Model as AST;

use RulerZ\Compiler\Context;
use RulerZ\Exception;
use RulerZ\Model;
use RulerZ\Target\GenericSqlVisitor;
use RulerZ\Target\Operators\Definitions as OperatorsDefinitions;

class DoctrineORMVisitor extends GenericSqlVisitor
{
    /**
     * @var DoctrineAutoJoin
     */
    private $autoJoin;

    public function __construct(Context $context, OperatorsDefinitions $operators, $allowStarOperator = true)
    {
        parent::__construct($context, $operators, $allowStarOperator);

        $this->autoJoin = new DoctrineAutoJoin($context['em'], $context['root_entities'], $context['root_aliases'], $context['joins']);
    }

    /**
     * @inheritDoc
     */
    public function getCompilationData()
    {
        return [
            'detectedJoins' => $this->autoJoin->getDetectedJoins(),
        ];
    }

    /**
     * {@inheritDoc}
     */
    public function visitAccess(AST\Bag\Context $element, &$handle = null, $eldnah = null)
    {
        return $this->autoJoin->buildAccessPath($element);
    }

    /**
     * {@inheritDoc}
     */
    public function visitParameter(Model\Parameter $element, &$handle = null, $eldnah = null)
    {
        // make it a placeholder
        return ':' . $element->getName();
    }

    private function getRootAlias()
    {
        return $this->context['root_aliases'][0];
    }
}

<?php

namespace RulerZ\Target\DoctrineORM;

use Hoa\Ruler\Model as AST;

use RulerZ\Compiler\Context;
use RulerZ\Exception;
use RulerZ\Model;
use RulerZ\Target\GenericSqlVisitor;
use RulerZ\Target\Operators\Definitions as OperatorsDefinitions;

class DoctrineORMVisitor extends GenericSqlVisitor
{
    /**
     * @var DoctrineAutoJoin
     */
    private $autoJoin;

    public function __construct(Context $context, OperatorsDefinitions $operators, $allowStarOperator = true)
    {
        parent::__construct($context, $operators, $allowStarOperator);

        $this->autoJoin = new DoctrineAutoJoin($context['em'], $context['root_entities'], $context['root_aliases'], $context['joins']);
    }

    /**
     * @inheritDoc
     */
    public function getCompilationData()
    {
        return [
            'detectedJoins' => $this->autoJoin->getDetectedJoins(),
        ];
    }

    /**
     * {@inheritDoc}
     */
    public function visitAccess(AST\Bag\Context $element, &$handle = null, $eldnah = null)
    {
        return $this->autoJoin->buildAccessPath($element);
    }

    /**
     * {@inheritDoc}
     */
    public function visitParameter(Model\Parameter $element, &$handle = null, $eldnah = null)
    {
        // placeholder for a positional parameters
        if (is_int($element->getName())) {
            return '?' . $element->getName();
        }

        // placeholder for a named parameter
        return ':' . $element->getName();
    }
}

Fix support for positional parameters in Doctrine ORM


<?php
namespace DMS\Bundle\TwigExtensionBundle\Twig\Date;

/**
 * Adds support for Padding a String in Twig
 */
class PadStringExtension extends \Twig_Extension
{
    /**
     * Name of Extension
     *
     * @return string
     */
    public function getName()
    {
        return 'PadStringExtension';
    }

    /**
     * Available filters
     *
     * @return array
     */
    public function getFilters()
    {
        return array(
            'padString' => new \Twig_Filter_Method($this, 'padStringFilter'),
        );
    }

    /**
     * Pads string on right or left with given padCharacter until string
     * reaches maxLength
     *
     * @param string  $value
     * @param string  $padCharacter
     * @param int     $maxLength
     * @param bool    $padLeft
     * @return string
     * @throws \InvalidArgumentException
     */
    public function padStringFilter($value, $padCharacter, $maxLength, $padLeft = true)
    {
        if ( ! is_int($maxLength) ) {
            throw new \InvalidArgumentException('Pad String Filter expects its second argument to be an integer');
        }

        if (function_exists('mb_strlen')) {
            $padLength = $maxLength - mb_strlen($value);
        } else {
            $padLength = $maxLength - strlen($value);
        }

        if ($padLength <= 0) {
            return $value;
        }

        $padString = str_repeat($padCharacter, $padLength);

        if ($padLeft) {
            return $padString . $value;
        }

        return $value . $padString;
    }
}

<?php
namespace DMS\Bundle\TwigExtensionBundle\Twig\Text;

/**
 * Adds support for Padding a String in Twig
 */
class PadStringExtension extends \Twig_Extension
{
    /**
     * Name of Extension
     *
     * @return string
     */
    public function getName()
    {
        return 'PadStringExtension';
    }

    /**
     * Available filters
     *
     * @return array
     */
    public function getFilters()
    {
        return array(
            'padString' => new \Twig_Filter_Method($this, 'padStringFilter'),
        );
    }

    /**
     * Pads string on right or left with given padCharacter until string
     * reaches maxLength
     *
     * @param string  $value
     * @param string  $padCharacter
     * @param int     $maxLength
     * @param bool    $padLeft
     * @return string
     * @throws \InvalidArgumentException
     */
    public function padStringFilter($value, $padCharacter, $maxLength, $padLeft = true)
    {
        if ( ! is_int($maxLength) ) {
            throw new \InvalidArgumentException('Pad String Filter expects its second argument to be an integer');
        }

        if (function_exists('mb_strlen')) {
            $padLength = $maxLength - mb_strlen($value);
        } else {
            $padLength = $maxLength - strlen($value);
        }

        if ($padLength <= 0) {
            return $value;
        }

        $padString = str_repeat($padCharacter, $padLength);

        if ($padLeft) {
            return $padString . $value;
        }

        return $value . $padString;
    }
}

Correct error in namespace declaration

Correct error in namespace declaration


<?php

class HelloWorldExtension extends Minz_Extension {
	public function init() {
		Minz_View::appendStyle($this->getFileUrl('style.css', 'css'));
		Minz_View::appendScript($this->getFileUrl('script.js', 'js'));

		$this->registerController('hello');
		$this->registerController('index');
		$this->registerViews();
	}
}

<?php

class HelloWorldExtension extends Minz_Extension {
	public function init() {
		Minz_View::appendStyle($this->getFileUrl('style.css', 'css'));
		Minz_View::appendScript($this->getFileUrl('script.js', 'js'));

		$this->registerController('hello');
		$this->registerController('index');
		$this->registerViews();

		$this->registerHook('entry_before_insert',
		                    array('HelloWorldExtension', 'setHelloWorldHook'));
	}

	public static function setHelloWorldHook($entry) {
		$entry->_content('Hello world!');
		return $entry;
	}
}

Add a test for entry_before_insert hook

Add a test for entry_before_insert hook


<?php
/**
 * Saves in cache using transient function of wordpress a request using callbacks
 * similar as wordpress does. Works only for WP.
 *
 * @package on-cache-please
 * @since 1.0.0
 */

if ( ! function_exists( 'on_cache_please' ) ) {
	/**
	 * Function to storage the cache on automatic.
	 *
	 * @since 1.0.0
	 * @param array $args {
	 *		An array of arguments.
	 *		@type string $key name. The name of the transient of the request.
	 *		@type string $key callback. The name of the function or the function
	 *									to execute that returns the data.
	 *		@type int    $key duration. The duration of the cache.
	 * }
	 */
	function on_cache_please( array $args = array() ) {
		$args = is_array( $args ) ? $args : array();
		$args = wp_parse_args( $args, array(
			'name' => '',
			'callback' => false,
			'duration' => HOUR_IN_SECONDS,
		));

		$data = get_transient( $args['name'] );
		if ( false === $data ) {
			if ( is_callable( $args['callback'] ) ) {
				$data = call_user_func( $args['callback'] );
				set_transient( $args['name'], $data, $args['duration'] );
			}
		}
		return $data;
	}
}

<?php
/**
 * Saves in cache using transient function of wordpress a request using callbacks
 * similar as wordpress does. Works only for WP.
 *
 * @package on-cache-please
 * @since 1.0.0
 */

if ( ! function_exists( 'on_cache_please' ) ) {
	/**
	 * Function to storage the cache on automatic.
	 *
	 * @since 1.0.0
	 * @param array $args {
	 *		An array of arguments.
	 *		@type string $key name. The name of the transient of the request.
	 *		@type string $key callback. The name of the function or the function
	 *									to execute that returns the data.
	 *		@type int    $key duration. The duration of the cache.
	 * }
	 */
	function on_cache_please( array $args = array() ) {
		$args = is_array( $args ) ? $args : array();
		$args = wp_parse_args( $args, array(
			'name' => '',
			'callback' => false,
			'duration' => HOUR_IN_SECONDS,
		));

		$data = get_transient( $args['name'] );
		if ( false === $data && is_callable( $args['callback'] ) ) {
			$data = call_user_func( $args['callback'] );
			set_transient( $args['name'], $data, $args['duration'] );
		}
		return $data;
	}
}

Simplify logic on the conditional

Simplify logic on the conditional


<?php
require '../scat.php';
require '../lib/catalog.php';

$parent= (int)$_REQUEST['parent'];

$departments= Model::factory('Department')
                ->where('parent_id', $parent)
                ->find_many();

if (!$departments)
  die_jsonp(array('error' => 'No departments in that department!'));

echo jsonp(array_map(function ($d) { return $d->as_array(); }, $departments));

<?php
require '../scat.php';
require '../lib/catalog.php';

$parent= (int)$_REQUEST['parent'];

$departments= Model::factory('Department')
                ->where('parent_id', $parent)
                ->order_by_asc('name')
                ->find_many();

if (!$departments)
  die_jsonp(array('error' => 'No departments in that department!'));

echo jsonp(array_map(function ($d) { return $d->as_array(); }, $departments));

Make sure to sort departments by name

Make sure to sort departments by name


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

$name= $_REQUEST['name'];
$company= $_REQUEST['company'];
$phone= $_REQUEST['phone'];
if (empty($name) && empty($company) && empty($phone))
  die_jsonp("You need to supply at least a name, company, or phone number.");

$list= array();
foreach(array('name', 'company', 'address',
              'email', 'phone', 'tax_id') as $field) {
  $list[]= "$field = '" . $db->escape($_REQUEST[$field]) . "', ";
}

if ($_REQUEST['phone']) {
  $list[]= "loyalty_number = '" .
           preg_replace('/[^\d]/', '', $_REQUEST['phone']) .
           "', ";
}

$fields= join('', $list);

$q= "INSERT INTO person
        SET $fields
        active = 1";
$r= $db->query($q)
  or die_query($db, $q);

echo jsonp(array('person' => $db->insert_id));

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

$name= $_REQUEST['name'];
$company= $_REQUEST['company'];
$phone= $_REQUEST['phone'];
if (empty($name) && empty($company) && empty($phone))
  die_jsonp("You need to supply at least a name, company, or phone number.");

$list= array();
foreach(array('name', 'role', 'company', 'address',
              'email', 'phone', 'tax_id') as $field) {
  $list[]= "$field = '" . $db->escape($_REQUEST[$field]) . "', ";
}

if ($_REQUEST['phone']) {
  $list[]= "loyalty_number = '" .
           preg_replace('/[^\d]/', '', $_REQUEST['phone']) .
           "', ";
}

$fields= join('', $list);

$q= "INSERT INTO person
        SET $fields
        active = 1";
$r= $db->query($q)
  or die_query($db, $q);

echo jsonp(array('person' => $db->insert_id));

Save role when adding new person

Save role when adding new person


<?php

if (!defined('ENMDIR')) define('ENMDIR', EXTENSIONS . "/email_newsletter_manager");
if (!defined('ENVIEWS')) define('ENVIEWS', ENMDIR . "/content/templates");

class contentExtensionemail_newsletter_managerpublishfield extends AjaxPage
{
    public function view()
    {
        $this->addHeaderToPage('Content-Type', 'text/html');
        $field_id = $this->_context[0];
        $entry_id = $this->_context[1];
        $this->_context['entry_id'] = $entry_id;
        try {

            $entry = EntryManager::fetch($entry_id);
            $entry = $entry[0];
            if (!is_a($entry, 'Entry')) {
                $this->_status = 404;

                return;
            }

            $field = FieldManager::fetch($field_id);
            if (!is_a($field, 'Field')) {
                $this->_status = 404;

                return;
            }
            $field->set('id', $field_id);

            $entry_data = $entry->getData();

            $data = new XMLElement('field');
            $field->displayPublishPanel($data, $entry_data[$field_id]);

            echo $data->generate(true);
            exit;
            $this->_Result->appendChild($data);
        } catch (Exception $e) {
        }
    }

    public function addScriptToHead()
    {
    }

    public function addStylesheetToHead()
    {
    }
}

<?php

if (!defined('ENMDIR')) define('ENMDIR', EXTENSIONS . "/email_newsletter_manager");
if (!defined('ENVIEWS')) define('ENVIEWS', ENMDIR . "/content/templates");

class contentExtensionemail_newsletter_managerpublishfield extends XMLPage
{
    public function view()
    {
        $this->addHeaderToPage('Content-Type', 'text/html');
        $field_id = $this->_context[0];
        $entry_id = $this->_context[1];
        $this->_context['entry_id'] = $entry_id;
        try {

            $entry = EntryManager::fetch($entry_id);
            $entry = $entry[0];
            if (!is_a($entry, 'Entry')) {
                $this->_status = 404;

                return;
            }

            $field = FieldManager::fetch($field_id);
            if (!is_a($field, 'Field')) {
                $this->_status = 404;

                return;
            }
            $field->set('id', $field_id);

            $entry_data = $entry->getData();

            $data = new XMLElement('field');
            $field->displayPublishPanel($data, $entry_data[$field_id]);

            echo $data->generate(true);
            exit;
            $this->_Result->appendChild($data);
        } catch (Exception $e) {
        }
    }

    public function addScriptToHead()
    {
    }

    public function addStylesheetToHead()
    {
    }
}

Replace deprecated class (since Symphony 2.6)


<?php
	/**
     * Documentation, License etc.
     *
     * @package Webserver
     */
    include_once 'Webserver.php';
    $server = new Webserver();
    echo "{response:".$server->parseRequest()."}";
    foreach ($_SERVER as $key => $value) {
    	echo "\n<br>$key => $value";
    }

Remove useless information from main printing


<?php get_header(); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
  <?php the_title(); ?>
  <?php the_content(); ?>
<?php endwhile; ?>
<?php else: ?>
<?php endif; ?>

<?php get_footer(); ?>

<?php get_header(); ?>

  <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

        <a href="<?php the_permalink(); ?>">
          <?php the_title(); ?>

      <?php the_date(); ?>

      <?php the_content(); ?>

  <?php endwhile; ?>
  <?php else: ?>
  <?php endif; ?>

<?php get_footer(); ?>

Add basic markup for posts listing.

Add basic markup for posts listing.


<?php

declare(strict_types=1);

namespace App\Observers;

use App\Jobs\PushToJedi;
use App\User;
use DateTime;

class UserObserver
{
    public function saved(User $user): void
    {
        PushToJedi::dispatch($user, User::class, $user->id, 'saved')->onQueue('jedi');
    }

    public function updated(User $user): void
    {
        if (null === $user->access_override_until || $user->access_override_until <= new DateTime()) {
            return;
        }

        PushToJedi::dispatch($user, User::class, $user->id, 'updated/access override expiration')
            ->delay($user->access_override_until)->onQueue('jedi');
    }
}

<?php

declare(strict_types=1);

namespace App\Observers;

use App\Jobs\PushToJedi;
use App\User;
use DateTime;

class UserObserver
{
    public function created(User $user): void
    {
        if ('cas_login' === $user->create_reason) {
            return;
        }

        UpdateMajorsForUser::dispatch($user)->onQueue('buzzapi');
    }

    public function saved(User $user): void
    {
        PushToJedi::dispatch($user, User::class, $user->id, 'saved')->onQueue('jedi');
    }

    public function updated(User $user): void
    {
        if (null === $user->access_override_until || $user->access_override_until <= new DateTime()) {
            return;
        }

        PushToJedi::dispatch($user, User::class, $user->id, 'updated/access override expiration')
            ->delay($user->access_override_until)->onQueue('jedi');
    }
}

Update majors when user is created

Update majors when user is created


<?php

namespace Enhavo\Bundle\ShopBundle\Form\Extension;

use Sylius\Bundle\ResourceBundle\Form\Type\ResourceTranslationsType;
use Sylius\Component\Resource\Translation\Provider\TranslationLocaleProviderInterface;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;

class ResourceTranslationsExtension extends AbstractTypeExtension
{
    /** @var string[] */
    private $definedLocalesCodes;

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

    public function __construct(TranslationLocaleProviderInterface $localeProvider)
    {
        $this->definedLocalesCodes = $localeProvider->getDefinedLocalesCodes();
        $this->defaultLocaleCode = $localeProvider->getDefaultLocaleCode();
    }

    public function finishView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['translation_locales'] = $this->definedLocalesCodes;

        $translationForms = [];

        foreach ($view as $locale => $child) {
            foreach ($child as $key => $childForm) {
                if (!isset($forms[$key])) {
                    $translationForms[$key] = [];
                }
                $translationForms[$key][$locale] = $childForm;
            }
        }

        $view->vars['translation_forms'] = $translationForms;

        return;
    }

    public function getExtendedTypes(): iterable
    {
        return [ResourceTranslationsType::class];
    }
}

<?php

namespace Enhavo\Bundle\ShopBundle\Form\Extension;

use Sylius\Bundle\ResourceBundle\Form\Type\ResourceTranslationsType;
use Sylius\Component\Resource\Translation\Provider\TranslationLocaleProviderInterface;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;

class ResourceTranslationsExtension extends AbstractTypeExtension
{
    /** @var string[] */
    private $definedLocalesCodes;

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

    public function __construct(TranslationLocaleProviderInterface $localeProvider)
    {
        $this->definedLocalesCodes = $localeProvider->getDefinedLocalesCodes();
        $this->defaultLocaleCode = $localeProvider->getDefaultLocaleCode();
    }

    public function finishView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['translation_locales'] = $this->definedLocalesCodes;

        $translationForms = [];

        foreach ($view as $locale => $child) {
            foreach ($child as $key => $childForm) {
                if (!isset($forms[$key])) {
                    $translationForms[$key] = [];
                }
                $translationForms[$key][$locale] = $childForm;
            }
        }

        $view->vars['translation_forms'] = $translationForms;

        return;
    }

    public static function getExtendedTypes(): iterable
    {
        return [ResourceTranslationsType::class];
    }
}

Update symfony and composer packages

Update symfony and composer packages


<?php
namespace Respect\Validation\Rules;

class PrimeNumber extends AbstractRule
{
    public function validate($input)
    {
        if(!is_numeric($input) || $input <= 1){
            return false;
        }

        if($input != 2 && ($input % 2) ==  0){
            return false;
        }

        for($i=2; $i < $input; $i++){
            if(($input % $i) == 0){
                return false;
            }
        }

        return true;
    }
}

<?php
namespace Respect\Validation\Rules;

class PrimeNumber extends AbstractRule
{
    public function validate($input)
    {
        if (!is_numeric($input) || $input <= 1) {
            return false;
        }

        if ($input != 2 && ($input % 2) ==  0) {
            return false;
        }

        for ($i = 2; $i < $input; $i++) {
            if (($input % $i) == 0) {
                return false;
            }
        }

        return true;
    }
}

Fix the coding standards problems.

Fix the coding standards problems.


<?php
/**
 * Default hero template file.
 *
 * This is the default hero image for page templates, called
 * 'block'. Strictly air specific.
 *
 * @Date:   2019-10-15 12:30:02
 * @Last Modified by:   Timi Wahalahti
 * @Last Modified time: 2021-01-12 16:00:20
 * @package air-light
 */

// Block settings
$block_class = is_front_page() ? ' block-front' : ' block-' . get_post_type();

// Featured image
$featured_image = has_post_thumbnail() ? wp_get_attachment_url( get_post_thumbnail_id() ) : THEME_SETTINGS['default_featured_image'];
?>

<section class="block block-hero<?php echo esc_attr( $block_class ); ?>" style="background-image: url('<?php echo esc_url( $featured_image ); ?>');">

<?php
/**
 * Default hero template file.
 *
 * This is the default hero image for page templates, called
 * 'block'. Strictly air specific.
 *
 * @Date:   2019-10-15 12:30:02
 * @Last Modified by:   Timi Wahalahti
 * @Last Modified time: 2021-01-12 16:00:20
 * @package air-light
 */

// Block settings
$block_class = is_front_page() ? ' block-hero-front' : ' block-hero-' . get_post_type();

// Featured image
$featured_image = has_post_thumbnail() ? wp_get_attachment_url( get_post_thumbnail_id() ) : THEME_SETTINGS['default_featured_image'];
?>

<section class="block block-hero<?php echo esc_attr( $block_class ); ?>" style="background-image: url('<?php echo esc_url( $featured_image ); ?>');">

Fix block class post type prefix

Fix block class post type prefix


<?php
namespace Auth;

trait LDAPSettableObject
{
    protected function setCachedOnlyProp($propName, $value)
    {
        if(in_array($propName, $this->cachedOnlyProps))
        {
            if(!is_object($this->ldapObj))
            {
                $this->setFieldLocal($propName, $value);
                return true;
            }
            throw new \Exception('Unsupported!');
        }
        return false;
    }

    protected function setMultiValueProp($propName, $value)
    {
        if(in_array($propName, $this->multiValueProps) && !is_array($value))
        {
            $this->setField($propName, array($value));
            return true;
        }
        return false;
    }

    public function __set($propName, $value)
    {
        if($this->setCachedOnlyProp($propName, $value) === true)
        {
            return;
        }
        if($this->setMultiValueProp($propName, $value) === true)
        {
            return;
        }
        $this->setField($propName, $value);
    }
}

/* vim: set tabstop=4 shiftwidth=4 expandtab: */

<?php
namespace Auth;

trait LDAPSettableObject
{
    protected function setCachedOnlyProp($propName, $value)
    {
        if(in_array($propName, $this->cachedOnlyProps))
        {
            if(!is_object($this->ldapObj))
            {
                $this->setFieldLocal($propName, $value);
                return true;
            }
            throw new \Exception('Unsupported!');
        }
        return false;
    }

    protected function setMultiValueProp($propName, $value)
    {
        if(in_array($propName, $this->multiValueProps) && !is_array($value))
        {
            if($value === null)
            {
                $this->setField($propName, $value);
            }
            else
            {
                $this->setField($propName, array($value));
            }
            return true;
        }
        return false;
    }

    public function __set($propName, $value)
    {
        if($this->setCachedOnlyProp($propName, $value) === true)
        {
            return;
        }
        if($this->setMultiValueProp($propName, $value) === true)
        {
            return;
        }
        $this->setField($propName, $value);
    }
}

/* vim: set tabstop=4 shiftwidth=4 expandtab: */

Allow blanking array properties on users


<?php
/* Note: Create a copy of this file with following name
   "config.php" (without quotes) and change your configuration.
 */
/* If hosted on root like 127.0.0.1/ then
   APP_NAME should be '/'
   Or else hosted on some directory like 127.0.0.1/salam/ then
   APP_NAME should be '/salam/'
 */
define('APP_NAME', '/');
?>

<?php
/* Note: Create a copy of this file with following name
   "config.php" (without quotes) and change your configuration.
 */
/* If hosted on root like 127.0.0.1/ then
   APP_NAME should be ''
   Or else hosted on some directory like 127.0.0.1/salam/ then
   APP_NAME should be '/salam'
 */
define('APP_NAME', '');
?>

Remove forward slash from APP_NAME

Remove forward slash from APP_NAME


<?php

class StoryTest extends TestCase {
	use Way\Tests\ModelHelpers;

    public function testBelongsToIssue()
    {
    	$this->assertBelongsTo('issue', 'Story');
    }

    public function testBelongsToAuthor()
    {
    	$this->assertBelongsTo('author', 'Story');
    }

    public function testHasOnePitch()
    {
    	$this->assertHasOne('pitch', 'Story');
    }

}

<?php
use Way\Tests\Factory;

class StoryTest extends TestCase {
	use Way\Tests\ModelHelpers;

    public function testBelongsToIssue()
    {
    	$this->assertBelongsTo('issue', 'Story');
    }

    public function testBelongsToAuthor()
    {
    	$this->assertBelongsTo('author', 'Story');
    }

    public function testHasOnePitch()
    {
    	$this->assertHasOne('pitch', 'Story');
    }

    public function testGetContent()
    {
    	Cache::forget('story-x');
    	$author = Factory::make('author');
    	$author->show = Author::SHOW_NICK;
    	$story = Factory::make('story', [
    		'author' => $author,
			'id' => 'x',
			'blurb' => 'This is a "thing"',
	   		'body' => "Lorem _ipsum_ dolor amet\n\nLorem--ipsum",
	   		'title' => "Big 'thing'",
    	]);
    	$return = [
    		'blurb' => "
This is a “thing”
\n",
    		'body' => "
Lorem ipsum dolor amet
\n\n
Lorem—ipsum
\n",
    		'title' => "Big ‘thing’",
    		'author' => $author->nickname,
    		'subhead' => $story->subhead,
    		'id' => 'x'
    	];
    	$this->assertEquals($return, $story->getContent());
    }

}

Add test for getContent() method

Add test for getContent() method


<?php

/**
 * Load admin dependencies.
 */
$tempdir = get_template_directory();
require_once($tempdir.'/admin/init.php');

/**
 * Theme set up settings.
 */
add_action('after_setup_theme', function()
{
	// Configure WP 2.9+ Thumbnails.
	add_theme_support('post-thumbnails');
	set_post_thumbnail_size(50, 50, true);
	add_image_size('thumbnail-large', 500, '', false);

	// Add support for post formats.
	add_theme_support('post-formats', ['aside', 'gallery', 'image', 'link', 'quote', 'video', 'audio']);
});

/**
 * Configure Default Title.
 */
add_filter('wp_title', function($title)
{
	$name = get_bloginfo('name');
	$description = get_bloginfo('description');

	if (is_front_page()) { return "$name - $description"; }

	return trim($title).' - '.$name;
});

/**
 * Configure Excerpt String.
 */
add_filter('excerpt_more', function($excerpt)
{
	return '…';
});

/**
 * Change Default Excerpt Length (default: 55).
 */
add_filter('excerpt_length', function($length)
{
	return 55;
});

<?php

/**
 * Load admin dependencies.
 */
$tempdir = get_template_directory();
require_once($tempdir.'/admin/init.php');

/**
 * Theme set up settings.
 */
add_action('after_setup_theme', function()
{
	// Configure WP 2.9+ Thumbnails.
	add_theme_support('post-thumbnails');
	set_post_thumbnail_size(50, 50, true);

	// add_image_size('thumbnail-large', 500, '', false);

	// Add support for post formats.
	add_theme_support('post-formats', ['aside', 'gallery', 'image', 'link', 'quote', 'video', 'audio']);
});

/**
 * Configure Default Title.
 */
add_filter('wp_title', function($title)
{
	$name = get_bloginfo('name');
	$description = get_bloginfo('description');

	if (is_front_page()) { return "$name - $description"; }

	return trim($title).' - '.$name;
});

/**
 * Configure Excerpt String.
 */
add_filter('excerpt_more', function($excerpt)
{
	return '…';
});

/**
 * Change Default Excerpt Length (default: 55).
 */
add_filter('excerpt_length', function($length)
{
	return 55;
});

Remove image size 500, add back when accutally needed.


<?php
//paths
define('ROOT_PATH', dirname(__FILE__, 2).'/');
define('INC_PATH', ROOT_PATH.'inc/');
define('VIEWS_PATH', INC_PATH.'views/');
define('ADMIN_VIEWS_PATH', INC_PATH.'views/admin/');
define('CONTROLLERS_PATH', INC_PATH.'controllers/');
define('MODELS_PATH', INC_PATH.'models/');
define('VIEW_HELPERS_PATH', INC_PATH.'view_helpers/');

require_once(INC_PATH.'environment_setup.php');
require_once(INC_PATH.'db.php');

define('BASE_URL','http://quotes.alaska.dev/');

define('STYLES_URL', BASE_URL.'styles/');
define('SCRIPTS_URL', BASE_URL.'scripts/');

<?php
//paths
define('ROOT_PATH', dirname(__FILE__, 2).'/');
define('INC_PATH', ROOT_PATH.'inc/');
define('VIEWS_PATH', INC_PATH.'views/');
define('ADMIN_VIEWS_PATH', INC_PATH.'views/admin/');
define('CONTROLLERS_PATH', INC_PATH.'controllers/');
define('MODELS_PATH', INC_PATH.'models/');
define('VIEW_HELPERS_PATH', INC_PATH.'view_helpers/');

require_once(INC_PATH.'environment_setup.php');
require_once(INC_PATH.'db.php');

define('BASE_URL','http://quotes.alaska.test/');

define('STYLES_URL', BASE_URL.'styles/');
define('SCRIPTS_URL', BASE_URL.'scripts/');

Update .dev domain for chrome

Update .dev domain for chrome


<?php

require __DIR__ . '/../src/functions.php';

spl_autoload_register(function($class) {
    if (strpos($class, 'FastRoute\\') === 0) {
        $dir = strcasecmp(substr($class, -4), 'Test') ? 'src/' : 'test/';
        $name = substr($class, strlen('FastRoute'));
        require __DIR__ . '/../' . $dir . strtr($name, '\\', DIRECTORY_SEPARATOR) . '.php';
    }
});

<?php

require_once __DIR__ . '/../src/functions.php';

spl_autoload_register(function($class) {
    if (strpos($class, 'FastRoute\\') === 0) {
        $dir = strcasecmp(substr($class, -4), 'Test') ? 'src/' : 'test/';
        $name = substr($class, strlen('FastRoute'));
        require __DIR__ . '/../' . $dir . strtr($name, '\\', DIRECTORY_SEPARATOR) . '.php';
    }
});

Change to require_once to prevent a PHP Fatal error during unit tests.


<?php

require_library('connectors/HydrothermalVentLarvaeAPI');

class test_connector_vent_larvae_api extends SimpletestUnitBase
{
    function testVentLarvaeAPI()
    {
        $url = "http://www.whoi.edu/vent-larval-id/MiscSpecies.htm";

        $taxa = HydrothermalVentLarvaeAPI::get_larvae_taxa($url);
        $this->assertTrue(is_array($taxa), 'Taxa should be an array');

        $taxon = $taxa[0];
        $this->assertIsA($taxon, 'SchemaTaxon', 'Response should be an array of SchemaTaxon');

        $dataObject = $taxon->dataObjects[0];
        $this->assertIsA($dataObject, 'SchemaDataObject', 'Taxon should have a data object');
    }
}

?>

<?php

require_library('connectors/HydrothermalVentLarvaeAPI');

class test_connector_vent_larvae_api extends SimpletestUnitBase
{
    function testVentLarvaeAPI()
    {
        //$url = "http://www.whoi.edu/vent-larval-id/MiscSpecies.htm";
        $url = "http://pandanus.eol.org/public/test_resources/MiscSpecies.htm";

        $taxa = HydrothermalVentLarvaeAPI::get_larvae_taxa($url);
        $this->assertTrue(is_array($taxa), 'Taxa should be an array');

        $taxon = $taxa[0];
        $this->assertIsA($taxon, 'SchemaTaxon', 'Response should be an array of SchemaTaxon');

        $dataObject = $taxon->dataObjects[0];
        $this->assertIsA($dataObject, 'SchemaDataObject', 'Taxon should have a data object');
    }
}

?>

Change source URL for test.

Change source URL for test.

git-svn-id: d46fe582d22b46b457d3ac1c55a88da2fbe913a1@1235 baf6b65b-9124-4dc3-b1c0-01155b4af546


<?
require_once ("common.php");
check_user ();
html_start ("Manage Playlist Templates");
?>

Add Time Slot

View/edit Schedule

Back to main menu

<?
html_end ();
?>

<?
require_once ("common.php");
check_user ();
html_start ("Manage Playlist Templates");
?>

Add Time Slot

View/edit Schedule

Copy Time Slots

Back to main menu

<?
html_end ();
?>

Access to the copy time slots page

Access to the copy time slots page

git-svn-id: 5a113f46df058f8047e288f4f3e948d899353d9a@236 410355f2-c4ea-45de-a5b5-301721f902b9


<?php
namespace App\Console\Command;

use Doctrine\ORM\EntityManager;
use Entity\Station;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class RestartRadio extends CommandAbstract
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this->setName('radio:restart')
            ->setDescription('Restart all radio stations.');
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        \App\Debug::setEchoMode(true);

        \App\Debug::log('Restarting all radio stations...');
        \App\Debug::divider();

        /** @var \Supervisor\Supervisor */
        $supervisor = $this->di['supervisor'];

        /** @var EntityManager $em */
        $em = $this->di['em'];
        $stations = $em->getRepository(Station::class)->findAll();

        $supervisor->stopAllProcesses();

        // Get rid of any processes running from legacy tooling.
        exec('sudo killall -9 liquidsoap icecast2 sc_serv');

        foreach($stations as $station)
        {
            /** @var Station $station */

            \App\Debug::log('Restarting station #'.$station->id.': '.$station->name);

            $station->writeConfiguration($this->di);

            \App\Debug::divider();
        }

        $supervisor->startAllProcesses();
    }
}

<?php
namespace App\Console\Command;

use Doctrine\ORM\EntityManager;
use Entity\Station;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class RestartRadio extends CommandAbstract
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this->setName('radio:restart')
            ->setDescription('Restart all radio stations.');
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        \App\Debug::setEchoMode(true);

        \App\Debug::log('Restarting all radio stations...');
        \App\Debug::divider();

        /** @var \Supervisor\Supervisor */
        $supervisor = $this->di['supervisor'];

        /** @var EntityManager $em */
        $em = $this->di['em'];
        $stations = $em->getRepository(Station::class)->findAll();

        $supervisor->stopAllProcesses();

        foreach($stations as $station)
        {
            /** @var Station $station */

            \App\Debug::log('Restarting station #'.$station->id.': '.$station->name);

            $station->writeConfiguration($this->di);

            \App\Debug::divider();
        }

        $supervisor->startAllProcesses();
    }
}

Remove the sudo killall from the CLI script, as it prompts for a password regardless of nopasswd settings. NOTE: if upgrading from a version prior to this version, a reboot may be required!


            Profile

            Messages

            <button class="cg fm oy ank" data-toggle="popover">
                image_uri }}">
            </button>

    <form class="ox oh i" role="search">

            <input type="text" class="form-control" data-action="grow" placeholder="Search">

    </form>

Profile

Notifications

Messages

Logout

Logout

Fix user image disaplay on navbar

Fix user image disaplay on navbar


@php
if (post_password_required()) {
  return;
}
@endphp

  @if (have_comments())

      {!! sprintf(_nx('One response to “%2$s”', '%1$s responses to “%2$s”', get_comments_number(), 'comments title', 'sage'), number_format_i18n(get_comments_number()), '' . get_the_title() . '') !!}

      {!! wp_list_comments(['style' => 'ol', 'short_ping' => true]) !!}

    @if (get_comment_pages_count() > 1 && get_option('page_comments'))

          @if (get_previous_comments_link())

@php(previous_comments_link(__('← Older comments', 'sage')))

          @endif
          @if (get_next_comments_link())

@php(next_comments_link(__('Newer comments →', 'sage')))

          @endif

    @endif
  @endif

  @if (!comments_open() && get_comments_number() != '0' && post_type_supports(get_post_type(), 'comments'))

      {{ __('Comments are closed.', 'sage') }}

  @endif

  @php(comment_form())

@php
if (post_password_required()) {
  return;
}
@endphp

  @if (have_comments())

      {!! sprintf(_nx('One response to “%2$s”', '%1$s responses to “%2$s”', get_comments_number(), 'comments title', 'sage'), number_format_i18n(get_comments_number()), '' . get_the_title() . '') !!}

      {!! wp_list_comments(['style' => 'ol', 'short_ping' => true]) !!}

    @if (get_comment_pages_count() > 1 && get_option('page_comments'))

          @if (get_previous_comments_link())

@php(previous_comments_link(__('← Older comments', 'sage')))

          @endif
          @if (get_next_comments_link())

@php(next_comments_link(__('Newer comments →', 'sage')))

          @endif

    @endif
  @endif

  @if (!comments_open() && get_comments_number() != '0' && post_type_supports(get_post_type(), 'comments'))

      {{ __('Comments are closed.', 'sage') }}

  @endif

  @php(comment_form(['class_submit' => 'button']))

Add button class to Comments form

Add button class to Comments form


<?php

return [
    'default' => 'fuzzy',

    'fieldName' => 'relevance',

    'drivers' => [

        'fuzzy' => [
            'class' => 'TomLingham\Searchy\SearchDrivers\FuzzySearchDriver',
        ],

        'ufuzzy' => [
            'class' => 'TomLingham\Searchy\SearchDrivers\FuzzySearchUnicodeDriver',
        ],

        'simple' => [
            'class' => 'TomLingham\Searchy\SearchDrivers\SimpleSearchDriver',
        ],

        'levenshtein' => [
            'class' => 'TomLingham\Searchy\SearchDrivers\LevenshteinSearchDriver',
        ],
    ],
];

<?php

return [
    'default' => 'ufuzzy',

    'fieldName' => 'relevance',

    'drivers' => [

        'fuzzy' => [
            'class' => 'TomLingham\Searchy\SearchDrivers\FuzzySearchDriver',
        ],

        'ufuzzy' => [
            'class' => 'TomLingham\Searchy\SearchDrivers\FuzzySearchUnicodeDriver',
        ],

        'simple' => [
            'class' => 'TomLingham\Searchy\SearchDrivers\SimpleSearchDriver',
        ],

        'levenshtein' => [
            'class' => 'TomLingham\Searchy\SearchDrivers\LevenshteinSearchDriver',
        ],
    ],
];

Fix for unicode characters support

Fix for unicode characters support


<?php
$c = 0;
foreach($items as $item) {
	if($c > $limit) {
		break;
	}
	$description = $item->content;
	if ($description) {
		$tooltip = substr(strip_tags($description,'
'),0,200)."...";
	} else {
		$tooltip = "";
	}
	$href = $item->url;
	$title = $item->title;
	print "
$title
\n";
	$c++;
}
?>

<?php
$c = 0;
foreach($items as $item) {
	if($c > $limit) {
		break;
	}
	$description = $item->content;
	if ($description) {
		if (function_exists('mb_substr')) {
			$tooltip = mb_substr(strip_tags($description,'
'),0,200, 'UTF-8')."...";
		} else {
			$tooltip = substr(strip_tags($description,'
'),0,200)."...";
		}
	} else {
		$tooltip = "";
	}
	$href = $item->url;
	$title = $item->title;
	print "
$title
\n";
	$c++;
}
?>

Trim tooltip correctly for multibyte chars


<?php
/**
 * AdminBuilderSubscriber.php
 *
 * @since 15/10/14
 * @author Gerhard Seidel <gseidel.message@googlemail.com>
 */

namespace esperanto\SliderBundle\EventListener;

use esperanto\AdminBundle\Event\RouteBuilderEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use esperanto\AdminBundle\Builder\Route\SyliusRouteBuilder;
use esperanto\AdminBundle\Builder\View\ViewBuilder;
use esperanto\AdminBundle\Event\BuilderEvent;

class AdminSliderBuilderSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(
            'esperanto_slider.slider.build_menu' => array('onBuildMenu', 0),
            'esperanto_slider.slider.build_table_route' => array('onBuildTableRoute', 0),
            'esperanto_slider.slider.build_index_route' => array('onBuildIndexRoute', 0),
        );
    }

    public function onBuildTableRoute(RouteBuilderEvent $event)
    {

    }

    public function onBuildIndexRoute(RouteBuilderEvent $event)
    {

    }

    public function onBuildMenu(MenuBuilderEvent $event)
    {
        $event->setBuilder(null);
    }
}

<?php
/**
 * AdminBuilderSubscriber.php
 *
 * @since 15/10/14
 * @author Gerhard Seidel <gseidel.message@googlemail.com>
 */

namespace esperanto\SliderBundle\EventListener;

use esperanto\AdminBundle\Event\RouteBuilderEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use esperanto\AdminBundle\Builder\Route\SyliusRouteBuilder;
use esperanto\AdminBundle\Builder\View\ViewBuilder;
use esperanto\AdminBundle\Event\BuilderEvent;
use esperanto\AdminBundle\Event\MenuBuilderEvent;

class AdminSliderBuilderSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(
            'esperanto_slider.slider.build_menu' => array('onBuildMenu', 0),
            'esperanto_slider.slider.build_table_route' => array('onBuildTableRoute', 0),
            'esperanto_slider.slider.build_index_route' => array('onBuildIndexRoute', 0),
        );
    }

    public function onBuildTableRoute(RouteBuilderEvent $event)
    {

    }

    public function onBuildIndexRoute(RouteBuilderEvent $event)
    {

    }

    public function onBuildMenu(MenuBuilderEvent $event)
    {
        $event->setBuilder(null);
    }
}

Fix missing use in SliderBundle

Fix missing use in SliderBundle


<?php

if (file_exists($this->DocPath()."/config.php")){
    $defaultConfig = include($this->DocPath()."/config.php");
}else {
    $defaultConfig = array();
}

$stagingConfig = array(
    'db' => array_merge($defaultConfig["db"],array(
        'dbname' => $defaultConfig["custom"]["staging_cache_general"]
    )),
    'custom' => array_merge($defaultConfig["custom"],array(
        'is_staging' => true,
    )),
    'cache' => array(
        'backendOptions' => array("cache_dir" => $this->DocPath('staging_cache_general')),
        'frontendOptions' => array()
    ),
    'httpCache' => array(
        'cache_dir' =>  $this->DocPath('staging_cache_templates_html')
    ),
    'template' => array(
        'cacheDir' => $this->DocPath('staging_cache_templates'),
        'compileDir' => $this->DocPath('staging_cache_templates')
    ),
    'hook' => array(
        'proxyDir' => $this->DocPath('staging_cache_proxies'),
        'proxyNamespace' => $this->App() . '_ProxiesStaging'
    ),
    'model' => array(
        'fileCacheDir'   => $this->DocPath('staging_cache_doctrine_filecache'),
        'attributeDir'   => $this->DocPath('staging_cache_doctrine_attributes'),
        'proxyDir'       => $this->DocPath('staging_cache_doctrine_proxies'),
        'proxyNamespace' => $this->App() . '\ProxiesStaging'
    )
);
return $stagingConfig;

<?php

if (file_exists($this->DocPath()."/config.php")){
    $defaultConfig = include($this->DocPath()."/config.php");
}else {
    $defaultConfig = array();
}

$stagingConfig = array(
    'db' => array_merge($defaultConfig["db"],array(
        'dbname' => $defaultConfig["custom"]["staging_database"]
    )),
    'custom' => array_merge($defaultConfig["custom"],array(
        'is_staging' => true,
    )),
    'cache' => array(
        'backendOptions' => array("cache_dir" => $this->DocPath('staging_cache_general')),
        'frontendOptions' => array()
    ),
    'httpCache' => array(
        'cache_dir' =>  $this->DocPath('staging_cache_templates_html')
    ),
    'template' => array(
        'cacheDir' => $this->DocPath('staging_cache_templates'),
        'compileDir' => $this->DocPath('staging_cache_templates')
    ),
    'hook' => array(
        'proxyDir' => $this->DocPath('staging_cache_proxies'),
        'proxyNamespace' => $this->App() . '_ProxiesStaging'
    ),
    'model' => array(
        'fileCacheDir'   => $this->DocPath('staging_cache_doctrine_filecache'),
        'attributeDir'   => $this->DocPath('staging_cache_doctrine_attributes'),
        'proxyDir'       => $this->DocPath('staging_cache_doctrine_proxies'),
        'proxyNamespace' => $this->App() . '\ProxiesStaging'
    )
);

return $stagingConfig;

Fix typo in default staging config

Fix typo in default staging config


<?php

namespace Deployer;

set('vhost_template', '<VirtualHost *:80>

    ServerAdmin webmaster@localhost

    DocumentRoot "{{document_root}}"

    <Directory "{{document_root}}">
        Options -Indexes
        Options FollowSymLinks MultiViews
        AllowOverride all
        Order allow,deny
        Allow from all
    </Directory>

{{vhost_server_names}}

</VirtualHost>

<VirtualHost *:443>

    ServerAdmin webmaster@localhost

    DocumentRoot "{{document_root}}"

    <Directory "{{document_root}}">
        Options -Indexes
        Options FollowSymLinks MultiViews
        AllowOverride all
        Order allow,deny
        Allow from all
    </Directory>

{{vhost_server_names}}

    SSLEngine on
    SSLCertificateFile "{{vhost_ssl_path}}/domain.pem"
    SSLCertificateKeyFile "{{vhost_ssl_path}}/domain.key"
    SSLCACertificateFile "{{vhost_ssl_path}}/domain.intermediate"

</VirtualHost>
');

set('vhost_path', getenv('VHOSTS_PATH'));
set('vhost_ssl_path', getenv('VHOSTS_SSLCERT_PATH'));

<?php

namespace Deployer;

set('vhost_template', '<VirtualHost *:80>

    ServerAdmin webmaster@localhost

    DocumentRoot "{{document_root}}"

    <Directory "{{document_root}}">
        Options -Indexes
        Options FollowSymLinks MultiViews
        AllowOverride all
        Order allow,deny
        Allow from all
    </Directory>

{{vhost_server_names}}

</VirtualHost>

<VirtualHost *:443>

    ServerAdmin webmaster@localhost

    DocumentRoot "{{document_root}}"

    <Directory "{{document_root}}">
        Options -Indexes
        Options FollowSymLinks MultiViews
        AllowOverride all
        Order allow,deny
        Allow from all
    </Directory>

{{vhost_server_names}}

    SSLEngine on
    SSLCertificateFile "{{vhost_sslcert_path}}/domain.pem"
    SSLCertificateKeyFile "{{vhost_sslcert_path}}/domain.key"
    SSLCACertificateFile "{{vhost_sslcert_path}}/domain.intermediate"

</VirtualHost>
');

set('vhost_path', getenv('VHOST_PATH'));
set('vhost_sslcert_path', getenv('VHOST_SSLCERT_PATH'));

Change name of vhost env vars

[TASK] Change name of vhost env vars


<?php

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

namespace AltThree\TestBench;

use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use ReflectionClass;

/**
 * This is the existence trait.
 *
 * @author Graham Campbell <graham@alt-three.com>
 */
trait ExistenceTrait
{
    public function testExistence()
    {
        $source = $this->getSourceNamespace();
        $tests = $this->getTestNamespace();
        $path = $this->getSourcePath();
        $len = strlen($path);

        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));

        foreach ($files as $file) {
            if ($file->getFilename()[0] === '.' || $file->isDir()) {
                continue;
            }

            $name = str_replace('/', '\\', strtok(substr($file->getPathname(), $len), '.'));

            $this->assertTrue(class_exists("{$source}{$name}"));
            $this->assertTrue(class_exists("{$tests}{$name}Test"));
        }
    }

    protected function getTestNamespace()
    {
        return (new ReflectionClass($this))->getNamespaceName();
    }

    protected function getSourceNamespace()
    {
        return str_replace('\\Tests\\', '\\', $this->getTestNamespace());
    }
}

<?php

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

namespace AltThree\TestBench;

use CallbackFilterIterator;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use ReflectionClass;

/**
 * This is the existence trait.
 *
 * @author Graham Campbell <graham@alt-three.com>
 */
trait ExistenceTrait
{
    /**
     * @dataProvider provideFilesToCheck
     */
    public function testExistence($class, $test)
    {
        $this->assertTrue(class_exists($class), "Expected the class {$class} to exist.");
        $this->assertTrue(class_exists($test), "Expected there to be tests for {$class}.");
    }

    public function provideFilesToCheck()
    {
        $source = $this->getSourceNamespace();
        $tests = $this->getTestNamespace();
        $path = $this->getSourcePath();
        $len = strlen($path);

        $files = new CallbackFilterIterator(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)), function ($file) {
            return $file->getFilename()[0] !== '.' && !$file->isDir();
        });

        return array_map(function ($file) use ($len, $source, $tests) {
            $name = str_replace('/', '\\', strtok(substr($file->getPathname(), $len), '.'));
            return ["{$source}{$name}", "{$tests}{$name}Test"];
        }, iterator_to_array($files));
    }

    protected function getTestNamespace()
    {
        return (new ReflectionClass($this))->getNamespaceName();
    }

    protected function getSourceNamespace()
    {
        return str_replace('\\Tests\\', '\\', $this->getTestNamespace());
    }
}

Use a data provider so we can show multiple failures


<?php

namespace CatLab\Requirements\Enums;

/**
 * Interface PropertyType
 * @package CatLab\RESTResource\Contracts
 */
class PropertyType
{
    const INTEGER = 'integer';
    const STRING = 'string';
    const DATETIME = 'datetime';
    const NUMBER = 'number';
    const BOOL = 'bool';
    const OBJECT = 'object';

    /**
     * @param $type
     * @return bool
     */
    public static function isNative($type)
    {
        return in_array($type, [
            self::INTEGER,
            self::STRING,
            self::DATETIME,
            self::NUMBER,
            self::BOOL
        ]);
    }

    /**
     * @param $type
     * @return bool
     */
    public static function isNumeric($type)
    {
        return in_array($type, [
            self::INTEGER,
            self::NUMBER
        ]);
    }
}

<?php

namespace CatLab\Requirements\Enums;

/**
 * Interface PropertyType
 * @package CatLab\RESTResource\Contracts
 */
class PropertyType
{
    const INTEGER = 'integer';
    const STRING = 'string';
    const DATETIME = 'datetime';
    const NUMBER = 'number';
    const BOOL = 'boolean';
    const OBJECT = 'object';

    /**
     * @param $type
     * @return bool
     */
    public static function isNative($type)
    {
        return in_array($type, [
            self::INTEGER,
            self::STRING,
            self::DATETIME,
            self::NUMBER,
            self::BOOL
        ]);
    }

    /**
     * @param $type
     * @return bool
     */
    public static function isNumeric($type)
    {
        return in_array($type, [
            self::INTEGER,
            self::NUMBER
        ]);
    }
}

Rename bool to boolean to keep consistency.


<?php

namespace Metrique\Building\Http\Composers;

use Illuminate\View\View;
use Metrique\Building\Building;

class BuildingViewComposer
{
    /**
     * The building repository.
     *
     * @var Building
     */
    protected $building;

    /**
     * Create a new profile composer.
     *
     * @param  Building  $building
     * @return void
     */
    public function __construct(Building $building)
    {
        $this->building = $building;
    }

    /**
     * Bind data to the view.
     *
     * @param  View  $view
     * @return void
     */
    public function compose(View $view)
    {
        $view->with('building', $this->building);
    }
}

<?php

namespace Metrique\Building\Http\Composers;

use Collective\Html\FormBuilder;
use Illuminate\View\View;
use Metrique\Building\Building;

class BuildingViewComposer
{
    /**
     * The building repository.
     *
     * @var Building
     */
    protected $building;

    /**
     * The form builder
     */
    protected $form;

    /**
     * Create a new profile composer.
     *
     * @param  Building  $building
     * @return void
     */
    public function __construct(Building $building, FormBuilder $form)
    {
        $this->building = $building;
        $this->form = $form;
    }

    /**
     * Bind data to the view.
     *
     * @param  View  $view
     * @return void
     */
    public function compose(View $view)
    {
        $view->with('building', $this->building);
        $view->with('form', $this->form);
    }
}

Add form helper to view composer

Add form helper to view composer


@if (isset($related['researchers']) && sizeof($related['researchers']['docs']) > 0)
    <?php
        // preparation
        $researchers_array = array();
        foreach ($related['researchers']['docs'] as $col) {
            $researchers_array[$col['display_relationship']][] = $col;
        }
    ?>

    Researchers:
    @foreach($researchers_array as $relation=>$researchers)
        @foreach($researchers as $key=>$col)

                {{$col['to_title']}}

            @if($key!=sizeof($researchers)-1)
                ,
            @endif
        @endforeach
        ({{ $relation }})
    @endforeach
    @if($related['researchers']['count'] > 5)

        View all {{ $related['researchers']['count'] }} related researchers
    @endif

@endif

@if (isset($related['researchers']) && sizeof($related['researchers']['docs']) > 0)
    <?php
        // preparation
        $researchers_array = array();
        foreach ($related['researchers']['docs'] as $col) {
            $col['display_relationship'] = str_replace("Participant, ","", $col['display_relationship']);
            $col['display_relationship'] = str_replace(", Participant","", $col['display_relationship']);
            $researchers_array[$col['display_relationship']][] = $col;
        }
        $displayNum = 0;
    ?>

    Researchers:
    @foreach($researchers_array as $relation=>$researchers)
        @foreach($researchers as $key=>$col)
            <?php $displayNum++; ?>

                {{$col['to_title']}}

            @if($relation!="Participant")
                ({{ $relation }})
            @endif
            @if($displayNum<$related['researchers']['count'])
                ,
            @endif
        @endforeach

    @endforeach
    @if($related['researchers']['count'] > 5)

        View all {{ $related['researchers']['count'] }} related researchers
    @endif

@endif

Remove (Participant) relationship displayed after the last non PI researcher CC2608


<?php
/**
 * @author         Pierre-Henry Soria <hello@ph7cms.com>
 * @copyright      (c) 2019, 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 / Module / SMS Verification / Inc / Class
 */
namespace PH7;

interface SmsProvidable
{
    /**
     * @param string $sPhoneNumber
     * @param string $sTextMessage
     *
     * @return bool
     */
    public function send($sPhoneNumber, $sTextMessage);
}

PSR-2: Add blank line before "namespace" declaration keyword


<?php
/**
 * @version     $Id$
 * @category    Nooku
 * @package     Nooku_Server
 * @subpackage  Newsfeeds
 * @copyright   Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
 * @license     GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link        http://www.nooku.org
 */

/**
 * Newsfeeds Database Table Class
 *
 * @author      Babs Gsgens <http://nooku.assembla.com/profile/babsgosgens>
 * @category    Nooku
 * @package     Nooku_Server
 * @subpackage  Newsfeeds
 */

class ComNewsfeedsDatabaseTableNewsfeeds extends KDatabaseTableDefault
{
    public function _initialize(KConfig $config)
    {
        $sluggable = KFactory::get('lib.koowa.database.behavior.sluggable',
            array('columns' => array('name'))
        );

         $config->append(array(
            'identity_column'    => 'id',
            'base'               => 'newsfeeds',
            'name'               => 'newsfeeds',
            'behaviors'          => array('lockable', 'orderable', $sluggable),
            'column_map'         => array(
                'enabled'   => 'published',
                'locked_on' => 'checked_out_time',
                'locked_by' => 'checked_out',
                'slug'      => 'alias'
            )
        ));

        parent::_initialize($config);
    }
}

<?php
/**
 * @version     $Id$
 * @category    Nooku
 * @package     Nooku_Server
 * @subpackage  Newsfeeds
 * @copyright   Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
 * @license     GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link        http://www.nooku.org
 */

/**
 * Newsfeeds Database Table Class
 *
 * @author      Babs Gsgens <http://nooku.assembla.com/profile/babsgosgens>
 * @category    Nooku
 * @package     Nooku_Server
 * @subpackage  Newsfeeds
 */

class ComNewsfeedsDatabaseTableNewsfeeds extends KDatabaseTableDefault
{
    public function _initialize(KConfig $config)
    {
         $sluggable = KDatabaseBehavior::factory('sluggable', array('columns' => array('name')));

         $config->append(array(
            'identity_column'    => 'id',
            'base'               => 'newsfeeds',
            'name'               => 'newsfeeds',
            'behaviors'          => array('lockable', 'orderable', $sluggable),
            'column_map'         => array(
                'enabled'   => 'published',
                'locked_on' => 'checked_out_time',
                'locked_by' => 'checked_out',
                'slug'      => 'alias'
            )
        ));

        parent::_initialize($config);
    }
}

Use KDatabaseBehavior::factory() to create the sluggable behavior.


<?php

/*
 * Poll for the response to an out-of-band challenge.
 *
 * This is called from AJAX, if the user has an out-of-band token. It acts as a proxy for the
 * `/validate/polltransaction`-endpoint of PrivacyIDEA.
 */

try{
    $authStateId = $_REQUEST['StateId'];
    $state = SimpleSAML_Auth_State::loadState($authStateId, 'privacyidea:privacyidea:init');
    SimpleSAML_Logger::debug("Loaded state privacyidea:privacyidea:init from polltransaction.php");
} catch (Exception $e){
}

if (isset($state)) {
    $serverconfig = $state['privacyidea:serverconfig'];
    $authToken = sspmod_privacyidea_Auth_utils::fetchAuthToken($serverconfig);
    $transaction_id = strval($state['privacyidea:privacyidea:checkTokenType']['transaction_id']);
    SimpleSAML_Logger::debug("Polling for transaction_id: " . $transaction_id);

    $result = sspmod_privacyidea_Auth_utils::curl(
        array(),
        array("authorization:" . $authToken),
        $serverconfig,
        "/validate/polltransaction/" . $transaction_id,
        "GET")
        ->result
        ->value;
}

echo isset($result) && $result ? "true" : "false";

?>

<?php

/*
 * Poll for the response to an out-of-band challenge.
 *
 * This is called from AJAX, if the user has an out-of-band token. It acts as a proxy for the
 * `/validate/polltransaction`-endpoint of PrivacyIDEA.
 */

try{
    $authStateId = $_REQUEST['StateId'];
    $state = SimpleSAML_Auth_State::loadState($authStateId, 'privacyidea:privacyidea:init');
    SimpleSAML_Logger::debug("Loaded state privacyidea:privacyidea:init from polltransaction.php");
} catch (Exception $e){
}

if (isset($state)) {
    $serverconfig = $state['privacyidea:serverconfig'];
    $authToken = sspmod_privacyidea_Auth_utils::fetchAuthToken($serverconfig);
    $transaction_id = $state['privacyidea:privacyidea:checkTokenType']['transaction_id'];
    SimpleSAML_Logger::debug("Polling for transaction_id: " . $transaction_id);

    $result = sspmod_privacyidea_Auth_utils::curl(
        array(),
        array("authorization:" . $authToken),
        $serverconfig,
        "/validate/polltransaction/" . $transaction_id,
        "GET")
        ->result
        ->value;
}

echo isset($result) && $result ? "true" : "false";

?>

Remove an unnecessary call to strval()

Remove an unnecessary call to strval()


<?php

namespace Fabs\Rest\Models;

use Fabs\Serialize\SerializableObject;

class ErrorModel extends SerializableObject
{

    /** @var string */
    public $status = null;
    /** @var string */
    public $error_message = null;
    /** @var null|SerializableObject */
    public $error_details = null;

    public function __construct()
    {
        parent::__construct();

        $this->addRenderIfNotNullCondition('error_details');
    }
}

<?php

namespace Fabs\Rest\Models;

use Fabs\Serialize\SerializableObject;

class ErrorResponseModel extends ResponseModel
{

    /** @deprecated
     *  @var string
     */
    public $error = null;
    /** @deprecated
     *  @var array|null
     */
    public $error_list = null;

    /** @var string */
    public $error_message = null;
    /** @var null|SerializableObject */
    public $error_details = null;

    public function __construct()
    {
        parent::__construct();

        $this->addRenderIfNotNullCondition('error');
        $this->addRenderIfNotNullCondition('error_list');
        $this->addRenderIfNotNullCondition('error_message');
        $this->addRenderIfNotNullCondition('error_details');
    }
}

ADD deprecated fields error and error_list to provide backwards compatibility


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

namespace Zend\I18n\Translator;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 * Translator.
 *
 * @category   Zend
 * @package    Zend_I18n
 * @subpackage Translator
 */
class TranslatorServiceFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        // Configure the translator
        $config = $serviceLocator->get('Configuration');
        $trConfig = isset($config['translator']) ? $config['translator'] : array();
        $translator = Translator::factory($trConfig);
        return $translator;
    }
}

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

namespace Zend\I18n\Translator;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

/**
 * Translator.
 *
 * @category   Zend
 * @package    Zend_I18n
 * @subpackage Translator
 */
class TranslatorServiceFactory implements FactoryInterface
{
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        // Configure the translator
        $config = $serviceLocator->get('Config');
        $trConfig = isset($config['translator']) ? $config['translator'] : array();
        $translator = Translator::factory($trConfig);
        return $translator;
    }
}

Replace 'Configuration' with 'Config' when retrieving configuration


<?php

/**
 * @copyright 2017 Vladimir Jimenez
 * @license   https://github.com/allejo/stakx/blob/master/LICENSE.md MIT
 */

namespace allejo\stakx\Object;

class DynamicPageView extends PageView
{
    /**
     * The Content Items that belong to this Page View. This array will only have elements if it is a dynamic Page View.
     *
     * @var ContentItem[]
     */
    private $contentItems;

    /**
     * {@inheritdoc}
     */
    public function __construct($filePath)
    {
        parent::__construct($filePath);

        $this->contentItems = array();
        $this->type = PageView::DYNAMIC_TYPE;
    }

    /**
     * Add a ContentItem to this Dynamic PageView
     *
     * @param ContentItem $contentItem
     */
    public function addContentItem (&$contentItem)
    {
        $filePath = $this->fs->getRelativePath($contentItem->getFilePath());

        $this->contentItems[$filePath] = &$contentItem;
        $contentItem->setPageView($this);
    }

    /**
     * Get all of the ContentItems that belong to this Dynamic PageView
     *
     * @return ContentItem[]
     */
    public function getContentItems ()
    {
        return $this->contentItems;
    }

    /**
     * Get the collection name this dynamic PageView is charged with
     *
     * @return string
     */
    public function getCollection ()
    {
        return $this->getFrontMatter(false)['collection'];
    }
}

<?php

/**
 * @copyright 2017 Vladimir Jimenez
 * @license   https://github.com/allejo/stakx/blob/master/LICENSE.md MIT
 */

namespace allejo\stakx\Object;

class DynamicPageView extends PageView
{
    /**
     * The Content Items that belong to this Page View. This array will only have elements if it is a dynamic Page View.
     *
     * @var ContentItem[]
     */
    private $contentItems;

    /**
     * {@inheritdoc}
     */
    public function __construct($filePath)
    {
        parent::__construct($filePath);

        $this->contentItems = array();
        $this->type = PageView::DYNAMIC_TYPE;
    }

    /**
     * Add a ContentItem to this Dynamic PageView
     *
     * @param ContentItem $contentItem
     */
    public function addContentItem (&$contentItem)
    {
        $filename = $this->fs->getBaseName($contentItem->getFilePath());

        $this->contentItems[$filename] = &$contentItem;
        $contentItem->setPageView($this);
    }

    /**
     * Get all of the ContentItems that belong to this Dynamic PageView
     *
     * @return ContentItem[]
     */
    public function getContentItems ()
    {
        return $this->contentItems;
    }

    /**
     * Get the collection name this dynamic PageView is charged with
     *
     * @return string
     */
    public function getCollection ()
    {
        return $this->getFrontMatter(false)['collection'];
    }
}

Store ContentItem refs in PageViews by basename


<?php
error_reporting(E_ALL & ~E_NOTICE);
define('MULTISITE', false);
define('SUBDOMAIN_INSTALL', false);
define('WPMU_PLUGIN_DIR', null);
define('WP_PLUGIN_DIR', null);
define('WP_USE_THEMES', false);

Update constants passed to `wp core is-installed`


<?php

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

namespace Symfony\Component\Form\Extension\HttpFoundation;

use Symfony\Component\Form\AbstractExtension;

/**
 * Integrates the HttpFoundation component with the Form library.
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class HttpFoundationExtension extends AbstractExtension
{
    protected function loadTypes()
    {
        return array(
            new Type\FormTypeHttpFoundationExtension(),
        );
    }
}

<?php

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

namespace Symfony\Component\Form\Extension\HttpFoundation;

use Symfony\Component\Form\AbstractExtension;

/**
 * Integrates the HttpFoundation component with the Form library.
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class HttpFoundationExtension extends AbstractExtension
{
    protected function loadTypeExtensions()
    {
        return array(
            new Type\FormTypeHttpFoundationExtension(),
        );
    }
}

[Form] Fix UnexpectedTypeException from HttpFoundation extension


<?php

namespace NyroDev\UtilityBundle\Form\Type;

use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\CallbackTransformer;

class ConfigType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->addModelTransformer(new CallbackTransformer(
                function ($original) {
                    return $original ? json_encode($original) : null;
                },
                function ($submitted) {
                    $ret = null;
                    if ($submitted) {
                        $ret = json_decode($submitted, true);
                        if (!$ret) {
                            $ret = false;
                        }
                    }

                    return $ret;
                }
            ));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions($resolver);
        $resolver
            ->setDefault('constraints', array(
                new \NyroDev\UtilityBundle\Validator\Constraints\ValidConfig(),
            ));
    }

    public function getParent()
    {
        return TextareaType::class;
    }
}

<?php

namespace NyroDev\UtilityBundle\Form\Type;

use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\CallbackTransformer;

class ConfigType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->addModelTransformer(new CallbackTransformer(
                function ($original) {
                    return $original && is_array($original) ? json_encode($original) : $original;
                },
                function ($submitted) {
                    $ret = null;
                    if ($submitted) {
                        $ret = json_decode($submitted, true);
                        if (!$ret) {
                            $ret = false;
                        }
                    }

                    return $ret;
                }
            ));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions($resolver);
        $resolver
            ->setDefault('constraints', array(
                new \NyroDev\UtilityBundle\Validator\Constraints\ValidConfig(),
            ));
    }

    public function getParent()
    {
        return TextareaType::class;
    }
}

Fix configType when given value is already a stringify JSON


<?php
/**
 * This file is part of prooph/proophessor-do.
 * (c) 2014-2016 prooph software GmbH <contact@prooph.de>
 * (c) 2015-2016 Sascha-Oliver Prolic <saschaprolic@googlemail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Prooph\ProophessorDo\Response;

use Prooph\Psr7Middleware\Response\ResponseStrategy;
use React\Promise\Promise;

final class JsonResponse implements ResponseStrategy
{
    public function fromPromise(Promise $promise)
    {
        $json = null;

        $promise->done(function ($data) use (&$json) {
            $json = $data;
        });

        return new JsonResponse($json);
    }
}

<?php
/**
 * This file is part of prooph/proophessor-do.
 * (c) 2014-2016 prooph software GmbH <contact@prooph.de>
 * (c) 2015-2016 Sascha-Oliver Prolic <saschaprolic@googlemail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace Prooph\ProophessorDo\Response;

use Prooph\Psr7Middleware\Response\ResponseStrategy;
use Psr\Http\Message\ResponseInterface;
use React\Promise\Promise;
use Zend\Diactoros\Response\JsonResponse as ZendJsonResponse;

final class JsonResponse implements ResponseStrategy
{
    public function fromPromise(Promise $promise): ResponseInterface
    {
        $json = null;

        $promise->done(function ($data) use (&$json) {
            $json = $data;
        });

        return new ZendJsonResponse($json);
    }
}

Fix method signature and wrong class import