<?php

declare(strict_types=1);

/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

namespace ParkManager\UI\Web\Action\Admin\User;

use ParkManager\Domain\User\User;
use ParkManager\UI\Web\Response\TwigResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

final class ShowUserAction
{
    /**
     * @Security("is_granted('ROLE_SUPER_ADMIN')")
     *
     * @Route(
     *     path="/user/{user}/show",
     *     methods={"GET", "HEAD"},
     *     name="park_manager.admin.show_user"
     * )
     */
    public function __invoke(Request $request, User $user): Response
    {
        return new TwigResponse('admin/user/show.html.twig', ['user' => $user]);
    }
}

<?php

declare(strict_types=1);

/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

namespace ParkManager\UI\Web\Action\Admin\User;

use ParkManager\Domain\User\User;
use ParkManager\UI\Web\Response\TwigResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

final class ShowUserAction
{
    /**
     * @Route(
     *     path="/user/{user}/show",
     *     methods={"GET", "HEAD"},
     *     name="park_manager.admin.show_user"
     * )
     */
    public function __invoke(Request $request, User $user): Response
    {
        return new TwigResponse('admin/user/show.html.twig', ['user' => $user]);
    }
}

Allow all admins to view user profile

[UI] Allow all admins to view user profile


<?php
declare(strict_types = 1);
/**
 * /src/Validator/Constraints/TimezoneValidator.php
 *
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */

namespace App\Validator\Constraints;

use App\Service\Localization;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use function array_column;
use function in_array;
use function is_string;

/**
 * Class TimezoneValidator
 *
 * @package App\Validator\Constraints
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */
class TimezoneValidator extends ConstraintValidator
{
    private Localization $localization;

    public function __construct(Localization $localization)
    {
        $this->localization = $localization;
    }

    /**
     * {@inheritdoc}
     */
    public function validate($value, Constraint $constraint): void
    {
        if (in_array($value, array_column($this->localization->getTimezones(), 'identifier'), true) !== true) {
            if (!is_string($value)) {
                $value = $value->getTimezone();
            }

            $this->context
                ->buildViolation(Timezone::MESSAGE)
                ->setParameter('{{ timezone }}', $value)
                ->setCode(Timezone::INVALID_TIMEZONE)
                ->addViolation();
        }
    }
}

<?php
declare(strict_types = 1);
/**
 * /src/Validator/Constraints/TimezoneValidator.php
 *
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */

namespace App\Validator\Constraints;

use App\Service\Localization;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use function array_column;
use function in_array;
use function is_string;

/**
 * Class TimezoneValidator
 *
 * @package App\Validator\Constraints
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */
class TimezoneValidator extends ConstraintValidator
{
    public function __construct(
        private Localization $localization,
    ) {
    }

    /**
     * {@inheritdoc}
     */
    public function validate($value, Constraint $constraint): void
    {
        if (in_array($value, array_column($this->localization->getTimezones(), 'identifier'), true) !== true) {
            $this->context
                ->buildViolation(Timezone::MESSAGE)
                ->setParameter('{{ timezone }}', !is_string($value) ? $value->getTimezone() : $value)
                ->setCode(Timezone::INVALID_TIMEZONE)
                ->addViolation();
        }
    }
}

Use PHP 8 constructor property promotion


<?php
/* @var $installer Ikonoshirt_Pbkdf2_Model_Mysql4_Setup */
$installer = $this;

$installer->startSetup();

$installer->getConnection()->modifyColumn($installer->getTable('admin/user'),
    'password', 'VARCHAR(800) default NULL');

$select = $installer->getConnection()->select();
$select->from($installer->getTable('eav/entity_type'), 'entity_type_id')->where('entity_type_code = ?', 'customer');
$id = $installer->getConnection()->fetchOne($select);

$installer->getConnection()->update($installer->getTable('eav/attribute'), array('backend_type' => 'text'), "attribute_code = 'password_hash' AND entity_type_id = $id");

// TODO copy all passwords to the eav_entity_text table and encrypt the hashes with PBKDF2

$installer->endSetup();

<?php
/* @var $installer Ikonoshirt_Pbkdf2_Model_Mysql4_Setup */
$installer = $this;

$installer->startSetup();

$installer->getConnection()->modifyColumn(
    $installer->getTable('admin/user'), 'password', 'VARCHAR(800) default NULL'
);

$installer->updateAttribute('customer', 'password_hash', 'backend_type', 'text');

// TODO copy all passwords to the eav_entity_text table and encrypt the hashes with PBKDF2

$installer->endSetup();

Use eav setup updateAttribute() instead of raw sql


<?php

/**
 * Garp_Form_Element_Email
 *
 * @package Garp
 * @author Harmen Janssen <harmen@grrr.nl>
 */
class Garp_Form_Element_Email extends Garp_Form_Element_Text {

    public function init() {
        $this->addFilter('PregReplace', array('match' => '/\s+/', 'replace' => ''));
        $this->addValidator('EmailAddress', false);
    }

}

<?php

/**
 * Garp_Form_Element_Email
 *
 * @package Garp
 * @author Harmen Janssen <harmen@grrr.nl>
 */
class Garp_Form_Element_Email extends Garp_Form_Element_Text {

    public function init() {
        $this->addFilter(
            new Zend_Filter_PregReplace([
                'match' => '/\s+/', 'replace' => ''
            ])
        );
        $this->addValidator('EmailAddress', false);
    }

}

Fix error in ReflectionClass when adding filter

Apparently this fails in PHP8 because of how this resolves in a
ReflectioClass? I'm not entirely sure I get this, but this fixes it.


<?php

require __DIR__.'/../paths.php';
require VENDOR_DIR.'autoload.php';
require STENCIL_DIR.'stencil.php';

use Stencil\Stencil as Stencil;

class StencilTest extends PHPUnit_Framework_TestCase
{
  public function testVersion()
  {
    $stencil = new Stencil();

    $this->assertEquals($stencil->version(), VERSION);
  }
}

<?php

require_once __DIR__.'/../paths.php';
require_once VENDOR_DIR.'autoload.php';
require_once STENCIL_DIR.'stencil.php';

use Stencil\Stencil as Stencil;

class StencilTest extends PHPUnit_Framework_TestCase
{
  public function testVersion()
  {
    $stencil = new Stencil();

    $this->assertEquals($stencil->version(), VERSION);
  }
}

Change require statement to require_once


<?php

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

namespace CloudObjects\PhpMAE\DI;

use CloudObjects\SDK\ObjectRetriever;
use CloudObjects\PhpMAE\Engine, CloudObjects\PhpMAE\ClassRepository;

/**
 * The DynamicLoader allows accessing other classes that are not
 * statically defined as dependencies.
 */
class DynamicLoader {

    private $retriever;
    private $repository;

    public function __construct(ObjectRetriever $retriever, ClassRepository $repository) {
        $this->retriever = $retriever;
        $this->repository = $repository;
    }

    public function get($coid) {
        $object = $this->retriever->get($coid);
        return isset($object)
            ? $this->repository->createInstance($object)->get(Engine::SKEY)
            : null;
    }

}

<?php

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

namespace CloudObjects\PhpMAE\DI;

use Psr\Http\Message\RequestInterface;
use CloudObjects\SDK\ObjectRetriever;
use CloudObjects\PhpMAE\Engine, CloudObjects\PhpMAE\ClassRepository;

/**
 * The DynamicLoader allows accessing other classes that are not
 * statically defined as dependencies.
 */
class DynamicLoader {

    private $retriever;
    private $repository;

    public function __construct(ObjectRetriever $retriever, ClassRepository $repository) {
        $this->retriever = $retriever;
        $this->repository = $repository;
    }

    public function get($coid, RequestInterface $request = null) {
        $object = $this->retriever->get($coid);
        return isset($object)
            ? $this->repository->createInstance($object, $request)->get(Engine::SKEY)
            : null;
    }

}

Support passing request dynamically loaded classes


<?php

namespace AppBundle\API\Mapping;

use AppBundle\API\Webservice;
use AppBundle\Entity\FennecUser;
use Symfony\Component\HttpFoundation\ParameterBag;

class FullByOrganismName extends Webservice
{
    private $db;

    /**
     * @inheritdoc
     */
    public function execute(ParameterBag $query, FennecUser $user = null)
    {
        $this->db = $this->getManagerFromQuery($query)->getConnection();
        $query_get_mapping = <<<EOF
SELECT fennec_id, scientific_name
    FROM organism
EOF;
        $stm_get_mapping = $this->db->prepare($query_get_mapping);
        $stm_get_mapping->execute();

        $result = array();
        while($row = $stm_get_mapping->fetch(\PDO::FETCH_ASSOC)){
            $name = $row['scientific_name'];
            if(!array_key_exists($name, $result)){
                $result[$row['scientific_name']] = $row['fennec_id'];
            } else {
                if(! is_array($result[$name]) ){
                    $result[$name] = [$result[$name]];
                }
                $result[$name][] = $row['fennec_id'];
            }
        }

        return $result;
    }
}

<?php

namespace AppBundle\API\Mapping;

use AppBundle\API\Webservice;
use AppBundle\Entity\FennecUser;
use AppBundle\Service\DBVersion;
use Symfony\Component\HttpFoundation\ParameterBag;

class FullByOrganismName
{
    private $manager;

    /**
     * FullByOrganismName constructor.
     * @param $dbversion
     */
    public function __construct(DBVersion $dbversion)
    {
        $this->manager = $dbversion->getEntityManager();
    }

    /**
     * @inheritdoc
     */
    public function execute(ParameterBag $query, FennecUser $user = null)
    {
        return $this->manager->getRepository('AppBundle:Organism')->getFullIds();
    }
}

Update service for getting full organism names


<?php namespace Jaybizzle\Safeurl;

use Illuminate\Support\ServiceProvider;

class SafeurlServiceProvider extends ServiceProvider {

	/**
	 * Indicates if loading of the provider is deferred.
	 *
	 * @var bool
	 */
	protected $defer = false;

	/**
	 * Bootstrap the application events.
	 *
	 * @return void
	 */
	public function boot()
	{
		//
	}

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app['safeurl'] = $this->app->share(function($app)
		{
			return new Safeurl;
		});
	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return array();
	}

}

<?php namespace Jaybizzle\Safeurl;

use Illuminate\Support\ServiceProvider;

class SafeurlServiceProvider extends ServiceProvider {

	/**
	 * Indicates if loading of the provider is deferred.
	 *
	 * @var bool
	 */
	protected $defer = false;

	/**
	 * Bootstrap the application events.
	 *
	 * @return void
	 */
	public function boot()
	{
		$this->registerConfig();
	}

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app['safeurl'] = $this->app->share(function($app)
		{
			return new Safeurl;
		});
	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return array();
	}

	/**
	 * Register our config file
	 *
	 * @return void
	 */
	protected function registerConfig()
	{
		// The path to the user config file
		$userConfigPath    = app()->configPath() . '/packages/jaybizzle/safeurl/config.php';

		// Path to the default config
		$defaultConfigPath = __DIR__ . '/../../config/config.php';

		// Load the default config
		$config = $this->app['files']->getRequire($defaultConfigPath);

		if (file_exists($userConfigPath))
		{
			// User has their own config, let's merge them properly
			$userConfig = $this->app['files']->getRequire($userConfigPath);
			$config     = array_replace_recursive($config, $userConfig);
		}

		// Set each of the items like ->package() previously did
		$this->app['config']->set('safeurl::config', $config);
	}

}

Access package config L5 style

Access package config L5 style


<?php

namespace RCatlin\Blog\Behavior;

use Refinery29\ApiOutput\Resource\ResourceFactory;
use Refinery29\Piston\Response;

trait RenderResponse
{
    /**
     * @param Response $response
     * @param array    $result
     *
     * @return Response
     */
    public function renderResult(Response $response, array $result)
    {
        $response->setStatusCode(200);
        $response->setResult(
            ResourceFactory::result($result)
        );

        return $response->withHeader('Content-Type', 'application/json');
    }
}

<?php

namespace RCatlin\Blog\Behavior;

use Assert\Assertion;
use Refinery29\ApiOutput\Resource\ResourceFactory;
use Refinery29\Piston\Response;

trait RenderResponse
{
    /**
     * @param Response $response
     * @param array    $result
     * @param int      $status
     *
     * @return Response
     */
    public function renderResult(Response $response, array $result, $status = 200)
    {
        Assertion::integer($status);

        $response->setResult(
            ResourceFactory::result($result)
        );

        return $response
            ->withHeader('Content-Type', 'application/json')
            ->withStatus($status)
        ;
    }
}

Fix Rendering Response with Status Code

Fix Rendering Response with Status Code


<?php

/**
 * Service for the Salesforce data API.
 *
 * @license http://opensource.org/licenses/MIT The MIT License (MIT)
 */

namespace Salesforce\Service;

use GuzzleHttp\ClientInterface as HttpClientInterface;

use skyflow\Domain\OAuthUser;
use skyflow\Service\OAuthServiceInterface;
use skyflow\Service\RestOAuthAuthenticatedService;

use Salesforce\Domain\SalesforceUser;

/**
 * Service for the Salesforce data API.
 */
class SalesforceDataService extends RestOAuthAuthenticatedService
{
    /**
     * Send a SOQL query to Salesforce data API.
     *
     * @param  string $query The SOQL query string.
     * @return string Response as string encoded in JSON format.
     */
    public function query($query)
    {
        $response = $this->httpGet(
            "/query",
            array(
                "q" => rtrim($query, ';')
            ),
            array(
                'Authorization', 'OAuth ' . $this->getUser()->getAccessToken()
            )
        );

        return $response->json();
    }

    /**
     * Get SObjects metadata.
     *
     * @return string Response as string encoded in JSON format.
     */
    public function sobjects()
    {
        $response = $this->httpGet(
            "/sobjects",
            array(),
            array(
                'Authorization', 'OAuth ' . $this->getUser()->getAccessToken()
            )
        );

        return $response->json();
    }
}

<?php

/**
 * Service for the Salesforce data API.
 *
 * @license http://opensource.org/licenses/MIT The MIT License (MIT)
 */

namespace Salesforce\Service;

use GuzzleHttp\ClientInterface as HttpClientInterface;

use skyflow\Domain\OAuthUser;
use skyflow\Service\OAuthServiceInterface;
use skyflow\Service\RestOAuthAuthenticatedService;

use Salesforce\Domain\SalesforceUser;

/**
 * Service for the Salesforce data API.
 */
class SalesforceDataService extends RestOAuthAuthenticatedService
{
    /**
     * Send a SOQL query to Salesforce data API.
     *
     * @param  string $query The SOQL query string.
     * @return string Response as string encoded in JSON format.
     */
    public function query($query)
    {
        $response = $this->httpGet(
            "/query",
            array(
                "q" => rtrim($query, ';')
            ),
            array(
                'Authorization' => 'OAuth ' . $this->getUser()->getAccessToken()
            )
        );

        return $response->json();
    }

    /**
     * Get SObjects metadata.
     *
     * @return string Response as string encoded in JSON format.
     */
    public function sobjects()
    {
        $response = $this->httpGet(
            "/sobjects",
            array(),
            array(
                'Authorization' => 'OAuth ' . $this->getUser()->getAccessToken()
            )
        );

        return $response->json();
    }
}

Fix typo in associative array

Fix typo in associative array


<?php

namespace DbMockLibrary\DbImplementations;

class Mongo extends AbstractMockLibrary
{
    /**
     * Insert into database
     *
     * @param string $collection
     * @param string $id
     *
     * @return mixed
     */
    protected function insert($collection, $id)
    {
        // TODO: Implement insert() method.
    }

    /**
     * Delete from database
     *
     * @param string $collection
     * @param array  $id
     *
     * @internal param array $data
     *
     * @return void
     */
    protected function delete($collection, $id)
    {
        // TODO: Implement delete() method.
    }
}

<?php

namespace DbMockLibrary\DbImplementations;

use DbMockLibrary\Exceptions\AlreadyInitializedException;
use DbMockLibrary\Exceptions\DbOperationFailedException;
use DbMockLibrary\AbstractMockLibrary;
use SimpleArrayLibrary\SimpleArrayLibrary;
use UnexpectedValueException;

class Mongo extends AbstractMockLibrary
{

    /**
     * @param array  $initialData
     * @param string $serverName
     * @param string $database
     * @param string $username
     * @param string $password
     *
     * @throws AlreadyInitializedException
     * @return void
     */
    public static function init(array $initialData, $serverName, $database, $username, $password)
    {
        if (!self::$instance) {
            if (empty($serverName) || !is_string($serverName)) {
                throw new UnexpectedValueException('Invalid server name');
            }
            if (empty($database) || !is_string($database)) {
                throw new UnexpectedValueException('Invalid database name');
            }
            if (empty($username) || !is_string($username)) {
                throw new UnexpectedValueException('Invalid username');
            }
            if (!is_string($password)) {
                throw new UnexpectedValueException('Invalid password');
            }
            if (!SimpleArrayLibrary::isAssociative($initialData) && !empty($initialData)) {
                throw new UnexpectedValueException('Invalid table names');
            }

            self::$instance              = new self();
            self::$instance->data        = self::$initialData = $initialData;

            // edit $data array where needed
            self::$instance->update();
        } else {
            throw new AlreadyInitializedException('MySQL library already initialized');
        }
    }
    /**
     * Insert into database
     *
     * @param string $collection
     * @param string $id
     *
     * @return mixed
     */
    protected function insert($collection, $id)
    {
        // TODO: Implement insert() method.
    }

    /**
     * Delete from database
     *
     * @param string $collection
     * @param array  $id
     *
     * @internal param array $data
     *
     * @return void
     */
    protected function delete($collection, $id)
    {
        // TODO: Implement delete() method.
    }
}

Work on mongo features started

Work on mongo features started


<?php

namespace App\Console\Commands\Import;

use Aic\Hub\Foundation\AbstractCommand as BaseCommand;

class ImportScheduleDaily extends BaseCommand
{

    protected $signature = 'import:daily';

    protected $description = 'Run all increment commands on sources that we\'re able to, and do a full refresh on sources that require it.';

    public function handle()
    {

        $this->call('import:collections');
        $this->call('import:collections-delete');
        $this->call('import:exhibitions-legacy');
        $this->call('import:events-ticketed');
        $this->call('import:events-legacy');
        $this->call('import:mobile');
        $this->call('import:products');
        $this->call('import:web');
        $this->call('import:digital-labels');

        // EventOccurrence is not included in import:web to avoid duplication
        $this->call('import:web-full', ['endpoint' => 'events/occurrences', '--yes' => 'default']);
    }

}

<?php

namespace App\Console\Commands\Import;

use Aic\Hub\Foundation\AbstractCommand as BaseCommand;

class ImportScheduleDaily extends BaseCommand
{

    protected $signature = 'import:daily';

    protected $description = 'Run all increment commands on sources that we\'re able to, and do a full refresh on sources that require it.';

    public function handle()
    {

        $this->call('import:collections');
        $this->call('import:collections-delete');
        $this->call('import:exhibitions-legacy');
        $this->call('import:events-ticketed');
        $this->call('import:events-legacy');
        $this->call('import:mobile');
        $this->call('import:products-full --yes');
        $this->call('import:web');
        $this->call('import:digital-labels');

        // EventOccurrence is not included in import:web to avoid duplication
        $this->call('import:web-full', ['endpoint' => 'events/occurrences', '--yes' => 'default']);
    }

}

Correct logical error that prevented new shop products from coming through [WEB-812]


<?php

/**
 * (c) Matthieu Bontemps <matthieu@knplabs.com>
 * (c) Thibault Duplessis <thibault.duplessis@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Bundle\DoctrineUserBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle as BaseBundle;
use Symfony\Component\EventDispatcher\Event;

class DoctrineUserBundle extends BaseBundle
{
    public function boot()
    {
        $this->container->get('event_dispatcher')->connect('security.token.unserialize', array($this, 'listenToSecurityTokenUnserialize'));
    }

    public function listenToSecurityTokenUnserialize(Event $event)
    {
        if($user = $event->getSubject()->getUser()) {
            $user = $this->container->get('doctrine_user.repository.user')->find($user->getId());
        }
    }
}

<?php

/**
 * (c) Matthieu Bontemps <matthieu@knplabs.com>
 * (c) Thibault Duplessis <thibault.duplessis@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Bundle\DoctrineUserBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle as BaseBundle;
use Symfony\Component\EventDispatcher\Event;

class DoctrineUserBundle extends BaseBundle
{
    public function boot()
    {
        $this->container->get('event_dispatcher')->connect('security.token.unserialize', array($this, 'listenToSecurityTokenUnserialize'));
    }

    public function listenToSecurityTokenUnserialize(Event $event)
    {
        if($user = $event->getSubject()->getUser()) {
            $this->container->get('doctrine_user.object_manager')->merge($user);
        }
    }
}

Use DocumentManager::merge instead of find


<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;

class ResetPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;

    /**
     * Where to redirect users after resetting their password.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }
}

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;

class ResetPasswordController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Password Reset Controller
    |--------------------------------------------------------------------------
    |
    | This controller is responsible for handling password reset requests
    | and uses a simple trait to include this behavior. You're free to
    | explore this trait and override any methods you wish to tweak.
    |
    */

    use ResetsPasswords;

    /**
     * Where to redirect users after resetting their password.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest');
    }
}

Fix redirect default on password reset

Fix redirect default on password reset


<?php

namespace Doctrine\Search\Exception;

/**
 * Exception thrown when an search query unexpectedly does not return any results.
 *
 * @author robo
 * @since 2.0
 */
class NoResultException extends DoctrineSearchException
{
    public function __construct()
    {
        parent::__construct('No result was found for query although at least one row was expected.');
    }
}

<?php

namespace Doctrine\Search\Exception;

/**
 * Exception thrown when an search query unexpectedly does not return any results.
 *
 * @author robo
 * @since 2.0
 */
class NoResultException extends DoctrineSearchException
{
    public function __construct($message = null)
    {
        parent::__construct($message ?: 'No result was found for query although at least one row was expected.');
    }
}

Allow overriding default exception message


<?php  namespace Rossedman\Teamwork;

use Rossedman\Teamwork\Traits\RestfulTrait;

class Time extends AbstractObject {

    use RestfulTrait;

    protected $wrapper  = 'time-entry';

    protected $endpoint = 'time_entries';

    /**
     * GET /time.json
     *
     * @return mixed
     */
    public function all($args = null)
    {
        $this->areArgumentsValid($args, [
            'page',
            'updatedAfterDate'
        ]);

        return $this->client->get($this->endpoint, $args)->response();
    }

    /**
     * GET /time.json
     *
     * @return mixed
     */
    public function allRaw($args = null)
    {
        return $this->client->get($this->endpoint, $args)->rawResponse();
    }
}

<?php  namespace Rossedman\Teamwork;

use Rossedman\Teamwork\Traits\RestfulTrait;

class Time extends AbstractObject {

    use RestfulTrait;

    protected $wrapper  = 'time-entry';

    protected $endpoint = 'time_entries';

    /**
     * GET /time.json
     *
     * @return mixed
     */
    public function all($args = null)
    {
        $this->areArgumentsValid($args, [
            'page',
            'updatedAfterDate'
        ]);

        return $this->client->get($this->endpoint, $args)->response();
    }

    /**
     * GET /time.json
     *
     * @return mixed
     */
    public function allRaw($args = null)
    {
        $this->areArgumentsValid($args, [
            'page',
            'updatedAfterDate'
        ]);

        return $this->client->get($this->endpoint, $args)->rawResponse();
    }
}

Validate parameters for the `allRaw` method too.


<?php
namespace SmoothPhp\CommandBus;

use Ramsey\Uuid\Uuid;
use SmoothPhp\Contracts\CommandBus\Command;

/**
 * Class Command
 * @package SmoothPhp\CommandBus
 * @author Simon Bennett <simon.bennett@smoothphp.com>
 */
abstract class BaseCommand implements Command
{
    /**
     * @var string
     */
    public $commandId;

    /**
     * Give the command a Uuid, Used to logging and auditing
     */
    public function __construct()
    {
        $this->commandId = (string)Uuid::uuid4();
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return get_class($this) . ':' . $this->commandId;
    }

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

<?php
namespace SmoothPhp\CommandBus;

use Ramsey\Uuid\Uuid;
use SmoothPhp\Contracts\CommandBus\Command;

/**
 * Class Command
 * @package SmoothPhp\CommandBus
 * @author Simon Bennett <simon.bennett@smoothphp.com>
 */
abstract class BaseCommand implements Command
{
    /**
     * @var string
     */
    private $commandId;

    /**
     * Give the command a Uuid, Used to logging and auditing
     */
    public function __construct()
    {
        $this->commandId = (string)Uuid::uuid4();
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return get_class($this) . ':' . $this->commandId;
    }

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

[Command] Check base command returns a UUID on creation


<?php

/**
 * This is project's console commands configuration for Robo task runner.
 *
 * @see http://robo.li/
 */

use Robo\Tasks;

class RoboFile extends Tasks
{
{
    // define public methods as commands
}

<?php
/**
 * This is project's console commands configuration for Robo task runner.
 *
 * @see http://robo.li/
 */
class RoboFile extends \Robo\Tasks
{
    // define public methods as commands
}

Revert "Codestyle fix for robo task file"

This reverts commit b2ba24e39ae8fdbd2476a71338bbcf0aa23c5953.


<?php

namespace AppBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * TraitTypeRepository
 *
 * This class was generated by the PhpStorm "Php Annotations" Plugin. Add your own custom
 * repository methods below.
 */
class TraitTypeRepository extends EntityRepository
{
    public function getNumber(){
        $query = $this->getEntityManager()->createQuery('SELECT COUNT(tt.id) FROM AppBundle\Entity\TraitType tt');
        return $query->getSingleScalarResult();
    }

    /**
     * @param $trait_type_id
     * @return array type, format, trait_type_id and ontology_url of specific trait
     */
    public function getInfo($trait_type_id){
        $qb = $this->getEntityManager()->createQueryBuilder();
        $qb->select('t.id AS trait_type_id', 't.type', 't.ontologyUrl', 'IDENTITY(t.traitFormat) AS trait_format_id', 't.description', 't.unit')
            ->from('AppBundle\Entity\TraitType', 't')
            ->where('t.id = :trait_type_id')
            ->setParameter('trait_type_id', $trait_type_id);
        $query = $qb->getQuery();
        return $query->getSingleResult();
    }
}

<?php

namespace AppBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * TraitTypeRepository
 *
 * This class was generated by the PhpStorm "Php Annotations" Plugin. Add your own custom
 * repository methods below.
 */
class TraitTypeRepository extends EntityRepository
{
    public function getNumber(){
        $query = $this->getEntityManager()->createQuery('SELECT COUNT(tt.id) FROM AppBundle\Entity\TraitType tt');
        return $query->getSingleScalarResult();
    }

    /**
     * @param $trait_type_id
     * @return array type, format, trait_type_id and ontology_url of specific trait
     */
    public function getInfo($trait_type_id){
        $qb = $this->getEntityManager()->createQueryBuilder();
        $qb->select('t.id AS traitTypeId', 't.type', 't.ontologyUrl', 'IDENTITY(t.traitFormat) AS trait_format_id', 't.description', 't.unit')
            ->from('AppBundle\Entity\TraitType', 't')
            ->where('t.id = :trait_type_id')
            ->setParameter('trait_type_id', $trait_type_id);
        $query = $qb->getQuery();
        return $query->getSingleResult();
    }
}

Change column names of result

Change column names of result


<?php namespace Applications;

use ReflectionClass;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;

class ApplicationsServiceProvider extends ServiceProvider
{

    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        // Find path to the package
        $applicationsFileName = with(new ReflectionClass('Applications\ApplicationsServiceProvider'))->getFileName();
        $applicationsPath = dirname($applicationsFileName);

        $this->loadViewsFrom($applicationsPath . '/../views', 'applications');

        include $applicationsPath . '/../routes.php';

    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->register(\Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class);
        $this->app->register(\Dingo\Api\Provider\LaravelServiceProvider::class);
        $this->app->register(\Barryvdh\Cors\ServiceProvider::class);

        $loader = AliasLoader::getInstance();
        $loader->alias('JWTAuth', \Tymon\JWTAuth\Facades\JWTAuth::class);
        $loader->alias('JWTFactory', \Tymon\JWTAuth\Facades\JWTFactory::class);

    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [];
    }

}

<?php namespace Applications;

use ReflectionClass;
use Illuminate\Foundation\AliasLoader;
use Illuminate\Support\ServiceProvider;

class ApplicationsServiceProvider extends ServiceProvider
{

    /**
     * Indicates if loading of the provider is deferred.
     *
     * @var bool
     */
    protected $defer = false;

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        // Find path to the package
        $applicationFileName = with(new ReflectionClass('Applications\ApplicationsServiceProvider'))->getFileName();
        $applicationPath = dirname($applicationFileName);

        $this->loadViewsFrom($applicationPath . '/../views', 'applications');

        include $applicationPath . '/../routes.php';

    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->register(\Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class);
        $this->app->register(\Dingo\Api\Provider\LaravelServiceProvider::class);
        $this->app->register(\Barryvdh\Cors\ServiceProvider::class);

        $this->app->register(\JwtAuth\JwtAuthServiceProvider::class);

        $loader = AliasLoader::getInstance();
        $loader->alias('JWTAuth', \Tymon\JWTAuth\Facades\JWTAuth::class);
        $loader->alias('JWTFactory', \Tymon\JWTAuth\Facades\JWTFactory::class);

    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return [];
    }

}

Update service provider Applications , JwtAuth


<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use App\Models\UserToken;
use Auth;
use Illuminate\Database\Eloquent\Model;

class UserController extends Controller
{
	protected $class = User::class;

	protected function registerMiddleware ()
	{
		$this->middleware('auth.token', ['except' => ['login', 'store']]);
		$this->middleware('auth.basic', ['only' => 'login']);
		$this->middleware('auth.admin', ['except' => ['login', 'store']]);
	}

	function store ()
	{
		$model = $response = parent::store();

		if ( ! ($model instanceof Model))
			return $response;

		$token = UserToken::randomToken();

		UserToken::create([
			'user_id' => $model->id,
			'token' => $token
		]);

		$model->token = $token;

		return $model;
	}

	function login ()
	{
		$user = Auth::user();

		return response()->json($user->toArray() + [
			'token' => $user->tokens()->first()->token
		]);
	}
}

<?php

namespace App\Http\Controllers\Api;

use App\Models\User;
use App\Models\UserToken;
use Auth;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\QueryException;
use Symfony\Component\HttpKernel\Exception\HttpException;

class UserController extends Controller
{
	protected $class = User::class;

	protected function registerMiddleware ()
	{
		$this->middleware('auth.token', ['except' => ['login', 'store']]);
		$this->middleware('auth.basic', ['only' => 'login']);
		$this->middleware('auth.admin', ['except' => ['login', 'store']]);
	}

	function store ()
	{
		try
		{
			$model = $response = parent::store();
		}
		catch (QueryException $e)
		{
			throw new HttpException(400, $e->getPrevious()->getMessage(),
				$e, $headers = [], $e->getCode());
		}

		if ( ! ($model instanceof Model))
			return $response;

		$token = UserToken::randomToken();

		UserToken::create([
			'user_id' => $model->id,
			'token' => $token
		]);

		$model->token = $token;

		return $model;
	}

	function login ()
	{
		$user = Auth::user();

		return response()->json($user->toArray() + [
			'token' => $user->tokens()->first()->token
		]);
	}
}

Improve error message for duplicates.

Improve error message for duplicates.


<?php

class HousePrice extends Module {

    public $url = "https://data.bathhacked.org/resource/ifh9-xtsp.json";

    function getData() {
        $postcodelat = self::$postCodeLoc[0];
        $postcodelong = self::$postCodeLoc[1];
        $this->url .= '?$where=date_of_transfer>%272014-01-01%27%20AND%20date_of_transfer<%272014-11-01%27%20AND%20within_circle(location,'.$postcodelong.','.$postcodelat.',1000)';
        return json_decode($this->fetch(), true);
    }
}

?>

<?php

class HousePrice extends Module {

    public $url = "https://data.bathhacked.org/resource/ifh9-xtsp.json";

    function getData() {
        $postcodelat = self::$postCodeLoc[0];
        $postcodelong = self::$postCodeLoc[1];
        $endDate = date('Y-m-d');
        $startDate = date('Y-m-d', time()-3*30*24*60*60);
        $this->url .= '?$where=date_of_transfer>%27'.$startDate.'%27%20AND%20date_of_transfer<%27'.$endDate.'%27%20AND%20within_circle(location,'.$postcodelong.','.$postcodelat.',1000)';

        return json_decode($this->fetch(), true);
    }
}

?>

Make Houses load from the last 3 months, not hardcoded.


<?php

namespace Outspaced\ChartsiaBundle\Chart\Renderer;

use Outspaced\ChartsiaBundle\Chart\Charts;
use Outspaced\ChartsiaBundle\Chart\Config;

class JavaScript
{
    /**
     * @param BaseChart $chart
     * @param \Twig_Environment $engine
     */
    public function renderWithTwig(Charts\BaseChart $chart, \Twig_Environment $engine)
    {
        $vars = [
            'title' => $this->renderTitle($chart->getTitle()),
            'title_color' => $this->renderTitleColor($chart->getTitle())
        ];

        $return = $engine->render(
            'OutspacedChartsiaBundle:Charts:javascript.html.twig',
            $vars
        );

        return $return;
    }

    protected function renderTitle(Config\Title $title = NULL)
    {
        if ($title === NULL) {
            return '';
        }

        return $title->getTitle();
    }

    protected function renderTitleColor(Config\Title $title = NULL)
    {
        if ($title === NULL || $title->getColor() === NULL) {
            return '';
        }

        return $title->getColor()->getColor();
    }

}

<?php

namespace Outspaced\ChartsiaBundle\Chart\Renderer;

use Outspaced\ChartsiaBundle\Chart\Charts;
use Outspaced\ChartsiaBundle\Chart\Config;

class JavaScript
{
    /**
     * @param BaseChart $chart
     * @param \Twig_Environment $engine
     */
    public function renderWithTwig(Charts\BaseChart $chart, \Twig_Environment $engine)
    {
        $vars = [
            'title' => $this->renderTitle($chart->getTitle()),
            'title_color' => $this->renderTitleColor($chart->getTitle()),

            // Move these out to methods
            'height' => $chart->getSize()->getHeight(),
            'width' => $chart->getSize()->getWidth(),
        ];

        $return = $engine->render(
            'OutspacedChartsiaBundle:Charts:javascript.html.twig',
            $vars
        );

        return $return;
    }

    protected function renderTitle(Config\Title $title = NULL)
    {
        if ($title === NULL) {
            return '';
        }

        return $title->getTitle();
    }

    protected function renderTitleColor(Config\Title $title = NULL)
    {
        if ($title === NULL || $title->getColor() === NULL) {
            return '';
        }

        return $title->getColor()->getColor();
    }

}

Put size elements into place for JS renderer


<?php
/**
 * Class HomePresenterTest
 *
 * @author: Jiří Šifalda <sifalda.jiri@gmail.com>
 * @date: 14.05.13
 */
namespace Flame\Tester\Example;

use Flame\Tester\SeleniumTestCase;

$container = require __DIR__ . '/bootstrap.php';

class HomePresenterTest extends SeleniumTestCase
{

	public function testOpen()
	{
		$this->open('http://www.facebook.com');
	}

}

id(new HomePresenterTest)->run();

<?php
/**
 * Class HomePresenterTest
 *
 * @author: Jiří Šifalda <sifalda.jiri@gmail.com>
 * @date: 14.05.13
 */
namespace Flame\Tester\Example;

use Flame\Tester\SeleniumTestCase;
use Flame\WebDriver\Element;
use Tester\Assert;

$container = require __DIR__ . '/bootstrap.php';

class HomePresenterTest extends SeleniumTestCase
{

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

		$this->setTestingUrl('jsifalda.name');
	}

	public function testName()
	{
		$this->open('/');
		Assert::equal(
			'Jiří Šifalda',
			$this->findElementBy(Element::CLASS_NAME, 'nine')
				->element(Element::TAG_NAME, 'h1')
				->text()
		);
	}

	public function testAboutMe()
	{
		$this->open('/');

		Assert::equal('Freelance Web Developer', $this->findElementBy(Element::CLASS_NAME, 'subhead')->text());
	}

}

id(new HomePresenterTest)->run();

Test of name & about me

Test of name & about me


<?php

namespace Ob\CacheNukeBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\HttpFoundation\Response;

class NukeController extends Controller
{
    public function indexAction()
    {
        $kernel = $this->get('kernel');
        $app = new Application($kernel);
        $app->setAutoExit(false);

        $input = new StringInput('cache:clear --env=prod');
        $output = new NullOutput();

        $app->run($input, $output);

        return new Response("Cache Nuked!");
    }
}

<?php

namespace Ob\CacheNukeBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Bundle\FrameworkBundle\Command\CacheClearCommand;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\HttpFoundation\Response;

class NukeController extends Controller
{
    public function indexAction()
    {
        $command = new CacheClearCommand();
        $command->setContainer($this->container);

        $input = new ArrayInput(array());
        $output = new NullOutput();

        // The @ is kinda bad, but there always was a "Warning: ini_set(): A session is active."
        // Which caused the response to be a 500.
        @$command->run($input, $output);

        return new Response("Cache Nuked!");
    }
}

Make it, you know, actually clear the cache


<?php
/**
 * abstract compiler pass for extref things
 */

namespace Graviton\DocumentBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
 * @link     http://swisscom.ch
 */
abstract class AbstractExtRefCompilerPass implements CompilerPassInterface
{
    /**
     * load services
     *
     * @param ContainerBuilder $container container builder
     *
     * @return void
     */
    final public function process(ContainerBuilder $container)
    {
        $gravitonServices = array_filter(
            $container->getServiceIds(),
            function ($id) {
                return substr($id, 0, 8) == 'graviton' &&
                    strpos($id, 'controller') !== false &&
                    $id !== 'graviton.rest.controller';
            }
        );
        $this->processServices($container, $gravitonServices);
    }

    /**
     * null implementation of method
     *
     * @param ContainerBuilder $container container
     * @param array            $services  services
     *
     * @return void
     */
    public function processServices(ContainerBuilder $container, $services)
    {
    }
}

<?php
/**
 * abstract compiler pass for extref things
 */

namespace Graviton\DocumentBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
 * @link     http://swisscom.ch
 */
abstract class AbstractExtRefCompilerPass implements CompilerPassInterface
{
    /**
     * load services
     *
     * @param ContainerBuilder $container container builder
     *
     * @return void
     */
    final public function process(ContainerBuilder $container)
    {
        $gravitonServices = array_filter(
            $container->getServiceIds(),
            function ($id) {
                return substr($id, 0, 8) == 'graviton' &&
                    strpos($id, 'controller') !== false &&
                    $id !== 'graviton.rest.controller';
            }
        );
        $this->processServices($container, $gravitonServices);
    }

    /**
     * abstract process method
     *
     * @param ContainerBuilder $container container
     * @param array            $services  services
     *
     * @return void
     */
    abstract public function processServices(ContainerBuilder $container, $services);
}

Define abstract base method as abstract

Define abstract base method as abstract


<?php
namespace Tbbc\MoneyBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;

class StorageCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $bundles = $container->getParameter('kernel.bundles');
        $storage = $container->getParameter('tbbc_money.pair.storage');

        //Determine if DoctrineBundle is defined
        if ('doctrine' === $storage) {
            if(!isset($bundles['DoctrineBundle'])) {
                throw new \RuntimeException('TbbcMoneyBundle - DoctrineBundle is needed to use Doctrine as a storage');
            }

            $storageDoctrineDefinition = new Definition('Tbbc\MoneyBundle\Pair\Storage\DoctrineStorage', array(
                new Reference('doctrine.orm.default_entity_manager'),
                $container->getParameter('tbbc_money.reference_currency')
            ));

            $container->setDefinition('tbbc_money.pair.doctrine_storage', $storageDoctrineDefinition);
            $container->getDefinition('tbbc_money.pair_manager')->replaceArgument(0, new Reference('tbbc_money.pair.doctrine_storage'));
        }
    }
}

<?php
namespace Tbbc\MoneyBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;

class StorageCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $bundles = $container->getParameter('kernel.bundles');
        $storage = $container->getParameter('tbbc_money.pair.storage');

        //Determine if DoctrineBundle is defined
        if ('doctrine' === $storage) {
            if(!isset($bundles['DoctrineBundle'])) {
                throw new \RuntimeException('TbbcMoneyBundle - DoctrineBundle is needed to use Doctrine as a storage');
            }

            $storageDoctrineDefinition = new Definition('Tbbc\MoneyBundle\Pair\Storage\DoctrineStorage', array(
                new Reference('doctrine.orm.entity_manager'),
                $container->getParameter('tbbc_money.reference_currency')
            ));

            $container->setDefinition('tbbc_money.pair.doctrine_storage', $storageDoctrineDefinition);
            $container->getDefinition('tbbc_money.pair_manager')->replaceArgument(0, new Reference('tbbc_money.pair.doctrine_storage'));
        }
    }
}

Fix when using multiple entity managers.

As per doctrine 2.4 default entity manager is referenced by doctrine.orm.entity_manager.


<?php

namespace RIPS\APIConnector;

use GuzzleHttp\Client;
use RIPS\APIConnector\Requests\UserRequests;
use RIPS\APIConnector\Requests\OrgRequests;
use RIPS\APIConnector\Requests\QuotaRequests;

class API
{
    // @var string - version number
    public $version = '0.0.1';

    // @var UserRequests
    public $users;

    // @var OrgRequests
    public $orgs;

    // @var QuotaRequests
    public $quotas;

    // @var array - Config values for $client
    protected $clientConfig = [
        'base_uri' => 'https://api-test2.internal.ripstech.com',
        'timeout' => 10,
        'connect_timeout' => 10,
    ];

    /**
     * Initialize new API
     *
     * @param string $username
     * @param string $password
     * @param array $clientConfig
     */
    public function __construct(string $username, string $password, array $clientConfig = [])
    {
        $mergedConfig = array_merge($this->clientConfig, $clientConfig, [
            'headers' => [
                'X-API-Username' => $username,
                'X-API-Password' => $password,
                'User-Agent' => "RIPS-API-Connector/{$this->version}",
            ],
        ]);

        $client = new Client($mergedConfig);
        $this->users = new UserRequests($client);
        $this->orgs = new OrgRequests($client);
        $this->quotas = new QuotaRequests($client);
    }
}

<?php

namespace RIPS\APIConnector;

use GuzzleHttp\Client;
use RIPS\APIConnector\Requests\UserRequests;
use RIPS\APIConnector\Requests\OrgRequests;
use RIPS\APIConnector\Requests\QuotaRequests;

class API
{
    // @var string - version number
    public $version = '0.0.1';

    // @var UserRequests
    public $users;

    // @var OrgRequests
    public $orgs;

    // @var QuotaRequests
    public $quotas;

    // @var array - Config values for $client
    protected $clientConfig = [
        'base_uri' => 'http://localhost:8000',
        'timeout' => 10,
        'connect_timeout' => 10,
        'http_errors' => false,
    ];

    /**
     * Initialize new API
     *
     * @param string $username
     * @param string $password
     * @param array $clientConfig
     */
    public function __construct(string $username, string $password, array $clientConfig = [])
    {
        $mergedConfig = array_merge($this->clientConfig, $clientConfig, [
            'headers' => [
                'X-API-Username' => $username,
                'X-API-Password' => $password,
                'User-Agent' => "RIPS-API-Connector/{$this->version}",
            ],
        ]);

        $client = new Client($mergedConfig);
        $this->users = new UserRequests($client);
        $this->orgs = new OrgRequests($client);
        $this->quotas = new QuotaRequests($client);
    }
}

Remove test server url and disable guzzle exceptions


<?php

namespace Code16\Sharp\View\Components;

use Code16\Sharp\View\Components\Utils\MenuItem;
use Illuminate\Support\Collection;
use Illuminate\View\Component;

class Menu extends Component
{
    public string $title;
    public ?string $username;
    public ?string $currentEntity;
    public bool $hasGlobalFilters;
    public Collection $items;

    public function __construct()
    {
        $this->title = config("sharp.name", "Sharp");
        $this->username = sharp_user()->{config("sharp.auth.display_attribute", "name")};
        $this->currentEntity = currentSharpRequest()->breadcrumb()->first()->key ?? null;
        $this->hasGlobalFilters = sizeof(config('sharp.global_filters') ?? []) > 0;
        $this->items = $this->getItems();
    }

    public function getItems(): Collection
    {
        return collect(config("sharp.menu", []))
            ->map(function($itemConfig) {
                return MenuItem::parse($itemConfig);
            })
            ->filter();
    }

    public function render()
    {
        return view('sharp::components.menu', [
            'component' => $this,
        ]);
    }
}

<?php

namespace Code16\Sharp\View\Components;

use Code16\Sharp\View\Components\Utils\MenuItem;
use Illuminate\Support\Collection;
use Illuminate\View\Component;

class Menu extends Component
{
    public string $title;
    public ?string $username;
    public ?string $currentEntity;
    public bool $hasGlobalFilters;
    public Collection $items;

    public function __construct()
    {
        $this->title = config("sharp.name", "Sharp");
        $this->username = sharp_user()->{config("sharp.auth.display_attribute", "name")};
        $this->currentEntity = currentSharpRequest()->breadcrumb()->first()->key ?? null;
        $this->hasGlobalFilters = sizeof(config('sharp.global_filters') ?? []) > 0;
        $this->items = $this->getItems();
    }

    public function getItems(): Collection
    {
        return collect(config("sharp.menu", []))
            ->map(function($itemConfig) {
                return MenuItem::parse($itemConfig);
            })
            ->filter()
            ->values();
    }

    public function render()
    {
        return view('sharp::components.menu', [
            'component' => $this,
        ]);
    }
}

Fix menu with missing values (->values()...)


<?php

namespace Korobi\WebBundle\Test\Unit;

use Korobi\WebBundle\Document\Chat;
use Korobi\WebBundle\IRC\Parser\IRCTextParser;
use Korobi\WebBundle\IRC\Parser\LogParser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\Translation\TranslatorInterface;

class LogParserTest extends WebTestCase {

    public function testTransformActorEscaping() {
        $sut = new LogParser(new DummyTranslator());
        $result = $sut->transformActor("HTML<marquee>yay</marquee>");
        $this->assertNotContains("<", $result, "Left angle bracket must not be in result.");
        $this->assertNotContains(">", $result, "Right angle bracket must not be in result.");
    }
}

class DummyTranslator implements TranslatorInterface {

    public function trans($id, array $parameters = array(), $domain = null, $locale = null) {
        return "Cat.";
    }

    public function transChoice($id, $number, array $parameters = array(), $domain = null, $locale = null) {
        return "Cat.";
    }

    public function setLocale($locale) {
        return;
    }

    public function getLocale() {
        return "Cat.";
    }
}

<?php

namespace Korobi\WebBundle\Test\Unit;

use Korobi\WebBundle\IRC\Parser\LogParser;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\Translation\TranslatorInterface;

class LogParserTest extends WebTestCase {

    public function testTransformActorEscaping() {
        $sut = new LogParser(new DummyTranslator());
        $result = $sut->transformActor("HTML<marquee>yay</marquee>");
        $this->assertNotContains("<", $result, "Left angle bracket must not be in result.");
        $this->assertNotContains(">", $result, "Right angle bracket must not be in result.");
    }
}

class DummyTranslator implements TranslatorInterface {

    public function trans($id, array $parameters = [], $domain = null, $locale = null) {
        return "Cat.";
    }

    public function transChoice($id, $number, array $parameters = [], $domain = null, $locale = null) {
        return "Cat.";
    }

    public function setLocale($locale) {
        return;
    }

    public function getLocale() {
        return "Cat.";
    }
}

Fix complaints from CS fixer

Fix complaints from CS fixer


<?php

namespace SwaggerGen\Swagger;

/**
 * Describes a Swagger Header object, which may be part of a Response.
 *
 * @package    SwaggerGen
 * @author     Martijn van der Lee <martijn@vanderlee.com>
 * @copyright  2014-2015 Martijn van der Lee
 * @license    https://opensource.org/licenses/MIT MIT
 */
class Header extends AbstractObject
{

	private $type;
	private $description;

	public function __construct(AbstractObject $parent, $type, $description = null)
	{
		parent::__construct($parent);

		$this->type = strtolower($type);
		if (!in_array($this->type, array('string', 'number', 'integer', 'boolean', 'array'))) {
			throw new \SwaggerGen\Exception('Header type not valid: ' . $this->type);
		}

		$this->description = $description;
	}

	public function handleCommand($command, $data = null)
	{
		switch (strtolower($command)) {
			case 'description':
				$this->description = $data;
				return $this;
		}

		return parent::handleCommand($command, $data);
	}

	public function toArray()
	{
		return self::array_filter_null(array_merge(array(
					'type' => $this->type,
					'description' => $this->description,
								), parent::toArray()));
	}

	public function __toString()
	{
		return __CLASS__ . ' ' . $this->type;
	}

}

<?php

namespace SwaggerGen\Swagger;

/**
 * Describes a Swagger Header object, which may be part of a Response.
 *
 * @package    SwaggerGen
 * @author     Martijn van der Lee <martijn@vanderlee.com>
 * @copyright  2014-2015 Martijn van der Lee
 * @license    https://opensource.org/licenses/MIT MIT
 */
class Header extends AbstractObject
{

	private $type;
	private $description;

	public function __construct(AbstractObject $parent, $type, $description = null)
	{
		parent::__construct($parent);

		$this->type = strtolower($type);
		if (!in_array($this->type, array('string', 'number', 'integer', 'boolean', 'array'))) {
			throw new \SwaggerGen\Exception('Header type not valid: ' . $type);
		}

		$this->description = $description;
	}

	public function handleCommand($command, $data = null)
	{
		switch (strtolower($command)) {
			case 'description':
				$this->description = $data;
				return $this;
		}

		return parent::handleCommand($command, $data);
	}

	public function toArray()
	{
		return self::array_filter_null(array_merge(array(
					'type' => $this->type,
					'description' => $this->description,
								), parent::toArray()));
	}

	public function __toString()
	{
		return __CLASS__ . ' ' . $this->type;
	}

}

Use original case for type in exception

Use original case for type in exception


<?php

namespace Ftrrtf\RollbarBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * @return \Symfony\Component\Config\Definition\Builder\TreeBuilder
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('ftrrtf_rollbar');

        $rootNode
            ->children()
                ->arrayNode('notifier')
                    ->children()
                        ->scalarNode('access_token')->isRequired()->end()
                        ->arrayNode('transport')
                            ->addDefaultsIfNotSet()
                            ->children()
                                ->scalarNode('type')->defaultValue('curl')->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
                ->arrayNode('environment')
                    ->children()
//                        ->scalarNode('host')->defaultNull()->end()
                        ->scalarNode('branch')->defaultValue('master')->end()
                        ->scalarNode('root_dir')->defaultValue('')->end()
                        ->scalarNode('environment')->defaultValue('unknown')->end()
                        ->scalarNode('framework')->end()
                    ->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}

<?php

namespace Ftrrtf\RollbarBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * This is the class that validates and merges configuration from your app/config files
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class}
 */
class Configuration implements ConfigurationInterface
{
    /**
     * @return \Symfony\Component\Config\Definition\Builder\TreeBuilder
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('ftrrtf_rollbar');

        $rootNode
            ->children()
                ->arrayNode('notifier')
                    ->children()
                        ->scalarNode('batched')->defaultFalse()->end()
                        ->scalarNode('access_token')->isRequired()->end()
                        ->arrayNode('transport')
                            ->addDefaultsIfNotSet()
                            ->children()
                                ->scalarNode('type')->defaultValue('curl')->end()
                            ->end()
                        ->end()
                    ->end()
                ->end()
                ->arrayNode('environment')
                    ->children()
//                        ->scalarNode('host')->defaultNull()->end()
                        ->scalarNode('branch')->defaultValue('master')->end()
                        ->scalarNode('root_dir')->defaultValue('')->end()
                        ->scalarNode('environment')->defaultValue('unknown')->end()
                        ->scalarNode('framework')->end()
                    ->end()
                ->end()
            ->end();

        return $treeBuilder;
    }
}

Add "batched" flag to config

Add "batched" flag to config


<?php
namespace Vela\Core;

use \Sabre\HTTP\Request;

Class User
{
  private $request;

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

  public function getUserAgent()
  {
      return $this->request->getRawServerValue('HTTP_USER_AGENT');
  }

  public function getUserIp()
  {
    $userIp = '';
    if (getenv('HTTP_CLIENT_IP'))
        $userIp = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $userIp = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $userIp = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $userIp = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
        $userIp = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $userIp = getenv('REMOTE_ADDR');
    else
        $userIp = 'UNKNOWN';

    return $userIp;
  }

}

<?php
namespace Vela\Core;

use \Sabre\HTTP\Request;

Class User
{
  private $request;

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

  public function getUserAgent()
  {
      return $this->request->getRawServerValue('HTTP_USER_AGENT');
  }

  public function getUserIp()
  {
    $userIp = '';
    if (getenv('HTTP_CLIENT_IP'))
        $userIp = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $userIp = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $userIp = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $userIp = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
        $userIp = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $userIp = getenv('REMOTE_ADDR');
    else
        $userIp = 'UNKNOWN';

    return $userIp;
  }

  public function isRobot($userAgent)
  {
    $robots = require 'src/Config/Robots.php';

    foreach ($robots as $robot)
    {
      if(strpos(strtolower($userAgent), $robot) !== false)
      {
        return true;
        break;
      }
    }

    return false;
  }

}

Move robot check code to USer class

Move robot check code to USer class


<?php

    namespace AmoCRM;

    class Client
    {
        private $parameters = null;

        public function __construct($domain, $login, $apikey)
        {
            $this->parameters = new ParamsBag();
            $this->parameters->addAuth('domain', $domain);
            $this->parameters->addAuth('login', $login);
            $this->parameters->addAuth('apikey', $apikey);
        }

        public function __get($name)
        {
            $classname = '\\AmoCRM\\' . ucfirst($name);

            if (!class_exists($classname)) {
                throw new ResourceException('Resource not exists: ' . $name);
            }

            return new $classname($this->parameters);
        }
    }

<?php

    namespace AmoCRM;

    class Client
    {
        private $parameters = null;

        public function __construct($domain, $login, $apikey)
        {
            $this->parameters = new ParamsBag();
            $this->parameters->addAuth('domain', $domain);
            $this->parameters->addAuth('login', $login);
            $this->parameters->addAuth('apikey', $apikey);
        }

        public function __get($name)
        {
            $classname = '\\AmoCRM\\' . ucfirst($name);

            if (!class_exists($classname)) {
                throw new ResourceException('Resource not exists: ' . $name);
            }

            // Чистим GET и POST от предыдущих вызовов
            $this->parameters->clearGet()->clearPost();

            return new $classname($this->parameters);
        }
    }

Clean GET and POST params before create an instance


<?php

namespace Modularity\Module\Social;

class Social extends \Modularity\Module
{
    public function __construct()
    {
        $this->register(
            'social',
            __("Social Media Feed", 'modularity'),
            __("Sociala Media Feeds", 'modularity'),
            __("Outputs a social media feed from desired username or hashtag (facebook, instagram, twitter, linkedin).", 'modularity'),
            array()
        );
    }

}

<?php

namespace Modularity\Module\Social;

class Social extends \Modularity\Module
{
    public function __construct()
    {
        $this->register(
            'social',
            __("Social Media Feed", 'modularity'),
            __("Sociala Media Feeds", 'modularity'),
            __("Outputs a social media feed from desired username or hashtag (facebook, instagram, twitter, linkedin).", 'modularity'),
            array(),
            null,
            null,
            0,
            true
        );
    }

}

Remove memcached from social media.

Remove memcached from social media.

This module has a built-in cache.


<?php
namespace envtesting;
/**
 * Copy & Paste example
 *
 * @author Roman Ozana <ozana@omdesign.cz>
 */
//if (file_exists(__DIR__ . '/Envtesting.php')) require_once __DIR__ . '/Envtesting.php';
//if (file_exists(__DIR__ . '/../Envtesting.php')) require_once __DIR__ . '/../Envtesting.php';

require_once __DIR__ . '/../envtesting/Autoloader.php';

Suite::instance('Copy & Paste example'); // change Suite name
Suite::instance()->failGroupOnFirstError(); // fail whole group on first error

// add some tests here

$mysql = Suite::instance()->mysql;
/** @var Suite $mysl */

$mysql->addTest('PDO', __DIR__ . '/../envtests/library/Pdo.php', 'library');
$mysql->addTest('PDO', __DIR__ . '/../envtests/library/Pdo.php', 'library');

// output
echo Suite::instance();

<?php
namespace envtesting;
/**
 * Copy & Paste example
 *
 * @author Roman Ozana <ozana@omdesign.cz>
 */
//if (file_exists(__DIR__ . '/Envtesting.php')) require_once __DIR__ . '/Envtesting.php';
//if (file_exists(__DIR__ . '/../Envtesting.php')) require_once __DIR__ . '/../Envtesting.php';

require_once __DIR__ . '/../envtesting/Autoloader.php';

Suite::instance('Copy & Paste example'); // change Suite name
Suite::instance()->failGroupOnFirstError(); // fail whole group on first error

// add some tests here

$mysql = Suite::instance()->mysql;
/** @var Suite $mysl */

$mysql->addTest('PDO', __DIR__ . '/../envtests/library/Pdo.php', 'library');
$mysql->addTest('PDO', __DIR__ . '/../envtests/library/Pdo.php', 'library');

// output
echo Suite::instance()->run();

Fix not calling run before outputing

Fix not calling run before outputing


<?php

namespace ZfcTwig\Service;

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

class TwigDefaultLoaderFactory implements FactoryInterface
{
    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return mixed
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        /** @var $templateStack \Zend\View\Resolver\TemplatePathStack */
        $templateStack = $serviceLocator->get('ViewTemplatePathStack');
        $loader        = new Twig_Loader_Filesystem('module/Application/view');

        foreach($templateStack->getPaths() as $path) {
            $loader->addPath($path);
        }

        return $loader;
    }
}

<?php

namespace ZfcTwig\Service;

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

class TwigDefaultLoaderFactory implements FactoryInterface
{
    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return mixed
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        /** @var $templateStack \Zend\View\Resolver\TemplatePathStack */
        $templateStack = $serviceLocator->get('ViewTemplatePathStack');
        $loader        = new Twig_Loader_Filesystem('module/Application/view');

        foreach($templateStack->getPaths() as $path) {
            if (file_exists($path)) {
                $loader->addPath($path);
            }
        }

        return $loader;
    }
}

Fix exception with adding paths that don't exist.


<?php
/**
 * @title            Singleton Helper Trait
 *
 * @author           Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright        (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / Framework / Pattern
 * @version          1.0
 */

namespace PH7\Framework\Pattern;

defined('PH7') or exit('Restricted access');

trait Singleton
{
    use Statik;

    /**
     * @staticvar object $_oInstance
     */
    protected static $_oInstance = null;

    /**
     * Get instance of class.
     *
     * @return self Returns the instance class or create initial instance of the class.
     */
    public static function getInstance()
    {
        return null === static::$_oInstance ? static::$_oInstance = new static : static::$_oInstance;
    }

    /**
     * Directly call "static::getInstance()" method when the object is called as a function.
     */
    public function __invoke()
    {
        return static::getInstance();
    }

    /**
     * Private serialize/unserialize method to prevent serializing/unserializing.
     */
    private function __wakeup()
    {
    }

    private function __sleep()
    {
    }
}

<?php
/**
 * @title            Singleton Helper Trait
 *
 * @author           Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright        (c) 2012-2018, Pierre-Henry Soria. All Rights Reserved.
 * @license          GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package          PH7 / Framework / Pattern
 * @version          1.0
 */

namespace PH7\Framework\Pattern;

defined('PH7') or exit('Restricted access');

trait Singleton
{
    use Statik;

    /**
     * @staticvar object $oInstance
     */
    protected static $oInstance = null;

    /**
     * Get instance of class.
     *
     * @return self Returns the instance class or create initial instance of the class.
     */
    public static function getInstance()
    {
        return null === static::$oInstance ? static::$oInstance = new static : static::$oInstance;
    }

    /**
     * Directly call "static::getInstance()" method when the object is called as a function.
     */
    public function __invoke()
    {
        return static::getInstance();
    }

    /**
     * Private serialize/unserialize method to prevent serializing/unserializing.
     */
    private function __wakeup()
    {
    }

    private function __sleep()
    {
    }
}

Remove _ prefix for private class attribute

Was from Pear coding conventions but doesnt make sense anymore since PHP has now access modifiers


<?php

namespace Annotate\Framework\ComponentModel;

use Annotate\Framework\Application\Components\BaseComponent;
use Annotate\Framework\ComponentModel\Forms\IFillable;
use Nette;
use Nette\Application\UI as UI;
use Nextras\Forms\Rendering\Bs3FormRenderer;

abstract class Form extends BaseComponent
{

	protected $addChildComponents = FALSE;

	public function build($args = [])
	{
	}

	protected function attached($parent)
	{
		parent::attached($parent);
		if ($parent instanceof UI\PresenterComponent) {
			if ($this instanceof IFillable) {
				$this->fillForm($this['form']);
			}
		}
		$this['form']->setRenderer(new Bs3FormRenderer);
	}

	abstract protected function createComponentForm();

}

<?php

namespace Annotate\Framework\ComponentModel;

use Annotate\Framework\Application\Components\BaseComponent;
use Annotate\Framework\ComponentModel\Forms\IFillable;
use Nette;
use Nette\Application\UI as UI;
use Nextras\Forms\Rendering\Bs3FormRenderer;

abstract class Form extends BaseComponent
{

	public $useBootstrap = TRUE;

	protected $addChildComponents = FALSE;

	public function build($args = [])
	{
	}

	protected function attached($parent)
	{
		parent::attached($parent);
		if ($parent instanceof UI\PresenterComponent) {
			if ($this instanceof IFillable) {
				$this->fillForm($this['form']);
			}
		}
		if ($this->useBootstrap) {
			$this['form']->setRenderer(new Bs3FormRenderer);
		}
	}

	abstract protected function createComponentForm();

}

Make Bootstrap form renderer optional

Make Bootstrap form renderer optional


<?php

// Shows the dashboard, if enabled
$app->get('/', [
    'middleware' => \Nord\ImageManipulationService\Http\Middleware\DashboardPageEnabledMiddleware::class,
    'uses'       => 'DashboardController@dashboard',
]);

// Shows the upload page, if enabled
$app->get('/upload', [
    'middleware' => \Nord\ImageManipulationService\Http\Middleware\UploadPageEnabledMiddleware::class,
    'uses'       => 'ImageController@index',
]);

// Serves an image
$app->get('/{path:.*}', [
    'as'         => 'serveImage',
    'middleware' => \Nord\ImageManipulationService\Http\Middleware\ServeImageAuthenticationMiddleware::class,
    'uses'       => 'ImageController@serveImage',
]);

// Stores an uploaded image to the source filesystem, then returns the path to it
$app->post('/upload', [
    'middleware' => [
        \Nord\ImageManipulationService\Http\Middleware\UploadAuthenticationMiddleware::class,
        \Nord\ImageManipulationService\Http\Middleware\ImageUploadFromFileValidatorMiddleware::class,
    ],
    'uses'       => 'ImageController@uploadImageFromFile',
]);

$app->post('/uploadFromUrl', [
    'middleware' => [
        \Nord\ImageManipulationService\Http\Middleware\UploadAuthenticationMiddleware::class,
        \Nord\ImageManipulationService\Http\Middleware\ImageUploadFromUrlValidatorMiddleware::class,
    ],
    'uses'       => 'ImageController@uploadImageFromUrl',
]);

<?php

// Shows the dashboard, if enabled
$app->get('/', [
    'middleware' => \Nord\ImageManipulationService\Http\Middleware\DashboardPageEnabledMiddleware::class,
    'uses'       => 'DashboardController@dashboard',
]);

// Shows the upload page, if enabled
$app->get('/upload', [
    'middleware' => \Nord\ImageManipulationService\Http\Middleware\UploadPageEnabledMiddleware::class,
    'uses'       => 'ImageController@index',
]);

// Serves an image
$app->get('/{path:.*}', [
    'as'         => 'serveImage',
    'middleware' => \Nord\ImageManipulationService\Http\Middleware\ServeImageAuthenticationMiddleware::class,
    'uses'       => 'ImageController@serveImage',
]);

// Health check
$app->get('/health', function() {
    return 'OK';
});

// Stores an uploaded image to the source filesystem, then returns the path to it
$app->post('/upload', [
    'middleware' => [
        \Nord\ImageManipulationService\Http\Middleware\UploadAuthenticationMiddleware::class,
        \Nord\ImageManipulationService\Http\Middleware\ImageUploadFromFileValidatorMiddleware::class,
    ],
    'uses'       => 'ImageController@uploadImageFromFile',
]);

$app->post('/uploadFromUrl', [
    'middleware' => [
        \Nord\ImageManipulationService\Http\Middleware\UploadAuthenticationMiddleware::class,
        \Nord\ImageManipulationService\Http\Middleware\ImageUploadFromUrlValidatorMiddleware::class,
    ],
    'uses'       => 'ImageController@uploadImageFromUrl',
]);

Add a basic health check route

Add a basic health check route


<?php

namespace Adldap\Configuration\Validators;

use Adldap\Configuration\ConfigurationException;

class IntegerValidator extends Validator
{
    /**
     * {@inheritdoc}
     */
    public function validate()
    {
        if (!is_int($this->value)) {
            throw new ConfigurationException("Option {$this->key} must be an integer.");
        }

        return true;
    }
}

<?php

namespace Adldap\Configuration\Validators;

use Adldap\Configuration\ConfigurationException;

class IntegerValidator extends Validator
{
    /**
     * {@inheritdoc}
     */
    public function validate()
    {
        if (!is_numeric($this->value)) {
            throw new ConfigurationException("Option {$this->key} must be an integer.");
        }

        return true;
    }
}

Validate using is_numeric instead of is_int


<?php namespace Orchestra\Support;

use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\AliasLoader;

class MessagesServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app['orchestra.messages'] = $this->app->share(function () {
            return new Messages;
        });

        $this->app->booting(function () {
            $loader = AliasLoader::getInstance();
            $loader->alias('Orchestra\Messages', 'Orchestra\Support\Facades\Messages');
        });
    }

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $app = $this->app;

        $app->after(function () use ($app) {
            $app['orchestra.messages']->save();
        });
    }
}

<?php namespace Orchestra\Support;

use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\AliasLoader;

class MessagesServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bindShared('orchestra.messages', function () {
            return new Messages;
        });

        $this->app->booting(function () {
            $loader = AliasLoader::getInstance();
            $loader->alias('Orchestra\Messages', 'Orchestra\Support\Facades\Messages');
        });
    }

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $app = $this->app;

        $app->after(function () use ($app) {
            $app['orchestra.messages']->save();
        });
    }
}

Update service provider to use bindShared.

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


<?php

namespace UserControlSkeleton;

class Requests
{
	protected $data;

	public function __construct()
	{
		foreach ($_POST as $key => $value) {
			$this->data[$key] = $value;
		}
	}

	public function get($field)
	{
		return $this->data[$field];
	}
}

<?php

namespace UserControlSkeleton;

class Requests
{
	protected $data;

	public function __construct()
	{
		foreach ($_POST as $key => $value) {
			$this->data[$key] = $value;
		}
	}

	public function get($field)
	{
		if (!array_key_exists($field, $this->data)) {
			return;
		}

		return $this->data[$field];
	}
}

Add logic to get request to return error if key not found


<?php
class Kwf_Assets_Dependency_Decorator_StringReplace extends Kwf_Assets_Dependency_Decorator_Abstract
{
    private $_replacements;
    public function __construct(Kwf_Assets_Dependency_Abstract $dep, array $replacements)
    {
        parent::__construct($dep);
        $this->_replacements = $replacements;
    }

    protected function _getReplacements()
    {
        return $this->_replacements;
    }

    public function getContents($language)
    {
        $ret = $this->_dep->getContents($language);
        foreach ($this->_getReplacements() as $k=>$i) {
            $ret = str_replace($k, $i, $Ret);
        }
        return $ret;
    }

    public function getContentsPacked($language)
    {
        $ret = $this->_dep->getContentsPacked($language);
        foreach ($this->_getReplacements() as $k=>$i) {
            $ret->stringReplace($k, $i);
        }
        return $ret;
    }
}

<?php
class Kwf_Assets_Dependency_Decorator_StringReplace extends Kwf_Assets_Dependency_Decorator_Abstract
{
    private $_replacements;
    public function __construct(Kwf_Assets_Dependency_Abstract $dep, array $replacements)
    {
        parent::__construct($dep);
        $this->_replacements = $replacements;
    }

    protected function _getReplacements()
    {
        return $this->_replacements;
    }

    public function getContents($language)
    {
        $ret = $this->_dep->getContents($language);
        foreach ($this->_getReplacements() as $k=>$i) {
            $ret = str_replace($k, $i, $Ret);
        }
        return $ret;
    }

    public function getContentsPacked($language)
    {
        $ret = $this->_dep->getContentsPacked($language);
        $ret = clone $ret;
        foreach ($this->_getReplacements() as $k=>$i) {
            $ret->stringReplace($k, $i);
        }
        return $ret;
    }
}

Clone object before modifying it

Clone object before modifying it

fixes replacements done multiple times


<?php

namespace Pipe;

class ImportProcessor extends \MetaTemplate\Template\Base
{
    const IMPORT_PATTERN = '/
        @import[\s]*(?:"([^"]+)"|url\\((.+)\\));
    /xm';

    function render($context = null, $vars = array())
    {
        $data = preg_replace_callback(self::IMPORT_PATTERN, function($matches) use ($context) {
            if (!empty($matches[1])) {
                $path = $matches[1];
            } else if (!empty($matches[2])) {
                $path = $matches[2];
            }

            $resolvedPath = $context->resolve($path);

            if (!$resolvedPath) {
                return $matches[0];
            }

            $context->dependOn($resolvedPath);

            # Import source code without processing, for LESS files.
            return $context->evaluate($resolvedPath, array('processors' => array()));
        }, $this->getData());

        return $data;
    }
}

<?php

namespace Pipe;

class ImportProcessor extends \MetaTemplate\Template\Base
{
    const IMPORT_PATTERN = '/
        @import[\s]*(?:"([^"]+)"|url\\((.+)\\));
    /xm';

    function render($context = null, $vars = array())
    {
        $data = preg_replace_callback(self::IMPORT_PATTERN, function($matches) use ($context) {
            if (!empty($matches[1])) {
                $path = $matches[1];
            } else if (!empty($matches[2])) {
                $path = $matches[2];
            }

            $resolvedPath = $context->resolve($path);

            if (!$resolvedPath) {
                return $matches[0];
            }

            $context->dependOn($resolvedPath);

            # Import source code without processing, for LESS files.
            return $context->evaluate($resolvedPath, array('processors' => array())) . "\n";
        }, $this->getData());

        return $data;
    }
}

Add a newline after each imported asset, fixes LESS compile errors


<?php

class Bookmarks_Controller extends List_Controller {

    protected $view = 'interface.bookmarks';

    protected $viewdata = array (
            'recordToolbarView' => 'components.result-toolbar-common',
            'recordPaneView' => 'components.bookmarksrecordpane'
            );

    public function __construct() {
        parent::__construct();
        $this->records = new Bookmarks();
        $this->records->autosave = true;
    }

    public function post_add($record = null) {
        return json_encode(
            array(
                'message' => __('bookmarks.' . $this->bookmarks->add($record) . 'flash')->get(),
                'count' => $this->bookmarks->size()
            )
        );
    }

    public function get_add($record = null) {
        $this->bookmarks->add($record);
        return Redirect::to('bookmarks');
    }

    public function post_delete($record = null) {
        return json_encode(
            array(
                'message' => __('bookmarks.' . $this->bookmarks->remove($record) . 'flash')->get(),
                'count' => $this->bookmarks->size()
            )
        );
    }

    public function get_delete($record = null) {
        $this->bookmarks->remove($record);
        return Redirect::to('bookmarks');
    }

}

<?php

class Bookmarks_Controller extends List_Controller {

    protected $view = 'interface.bookmarks';

    protected $viewdata = array (
            'recordToolbarView' => 'components.result-toolbar-common',
            'recordPaneView' => 'components.bookmarksrecordpane'
            );

    public function __construct() {
        parent::__construct();
        $this->records = new Bookmarks();
        $this->records->autosave = true;
    }

    public function post_add($record = null) {
        return json_encode(
            array(
                'message' => __('bookmarks.' . $this->records->add($record) . 'flash')->get(),
                'count' => $this->records->size()
            )
        );
    }

    public function get_add($record = null) {
        $this->records->add($record);
        return Redirect::to('bookmarks');
    }

    public function post_delete($record = null) {
        return json_encode(
            array(
                'message' => __('bookmarks.' . $this->records->remove($record) . 'flash')->get(),
                'count' => $this->records->size()
            )
        );
    }

    public function get_delete($record = null) {
        $this->records->remove($record);
        return Redirect::to('bookmarks');
    }

}

Fix bookmark adding and removing

Fix bookmark adding and removing


<?php

class Ebanx_Gateway_Model_Import extends Mage_Directory_Model_Currency_Import_Abstract
{
	protected $_messages = array();
	/**
	 * @var \Ebanx\Benjamin\Facade
	 */
	protected $ebanx;

	/**
	 * Retrieve rate
	 *
	 * @param   string $currencyFrom
	 * @param   string $currencyTo
	 *
	 * @return  float|null
	 */
	protected function _convert( $currencyFrom, $currencyTo ) {
		$this->ebanx = Mage::getSingleton('ebanx/api')->ebanx();
		$rate = $this->ebanx->exchange()->fetchRate($currencyFrom, $currencyTo);
		return $rate ?: null;
	}
}

Add blank line before return

Add blank line before return


<?php

namespace tests\Http\Discovery;

use Http\Discovery\Exception\NotFoundException;
use Http\Discovery\Psr17FactoryDiscovery;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ServerRequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\UploadedFileFactoryInterface;
use Psr\Http\Message\UriFactoryInterface;

class Psr17FactoryDiscoveryTest extends TestCase
{
    /**
     * @dataProvider getFactories
     */
    public function testFind($method, $interface)
    {
        $callable = [Psr17FactoryDiscovery::class, $method];
        $client = $callable();
        $this->assertInstanceOf($interface, $client);
    }

    /**
     * @group NothingInstalled
     * @dataProvider getFactories
     */
    public function testNotFound($method)
    {
        $callable = [Psr17FactoryDiscovery::class, $method];
        $this->expectException(NotFoundException::class);
        $callable();
    }

    public function getFactories()
    {
        yield ['findRequestFactory', RequestFactoryInterface::class];
        yield ['findResponseFactory', ResponseFactoryInterface::class];
        yield ['findServerRequestFactory', ServerRequestFactoryInterface::class];
        yield ['findStreamFactory', StreamFactoryInterface::class];
        yield ['findUploadedFileFactory', UploadedFileFactoryInterface::class];
        yield ['findUrlFactory', UriFactoryInterface::class];
    }
}

<?php

namespace tests\Http\Discovery;

use Http\Discovery\Exception\NotFoundException;
use Http\Discovery\Psr17FactoryDiscovery;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ServerRequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\UploadedFileFactoryInterface;
use Psr\Http\Message\UriFactoryInterface;

class Psr17FactoryDiscoveryTest extends TestCase
{
    /**
     * @dataProvider getFactories
     */
    public function testFind($method, $interface)
    {
        $callable = [Psr17FactoryDiscovery::class, $method];
        $client = $callable();
        $this->assertInstanceOf($interface, $client);
    }

    /**
     * @group NothingInstalled
     * @dataProvider getFactories
     */
    public function testNotFound($method)
    {
        $callable = [Psr17FactoryDiscovery::class, $method];
        $this->expectException(NotFoundException::class);
        $callable();
    }

    public function getFactories()
    {
        yield ['findRequestFactory', RequestFactoryInterface::class];
        yield ['findResponseFactory', ResponseFactoryInterface::class];
        yield ['findServerRequestFactory', ServerRequestFactoryInterface::class];
        yield ['findStreamFactory', StreamFactoryInterface::class];
        yield ['findUploadedFileFactory', UploadedFileFactoryInterface::class];
        yield ['findUriFactory', UriFactoryInterface::class];
        yield ['findUrlFactory', UriFactoryInterface::class];
    }
}

Test the replacement method too

Test the replacement method too


<?php

namespace App\Policies;

use App\User;
use App\APIUser;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Http\Request;

class APIUserPolicy
{
    use HandlesAuthorization;

    public function view_in_admin(User $user) {
        if ($user->site_admin) {
            return true;
        }
    }

    public function get_all(User $user)
    {
        if ($user->site_admin) {
            return true;
        }
    }

    public function get(User $user, APIUser $api_user)
    {
        if ($user->site_admin) {
            return true;
        }
    }

    public function create(User $user)
    {
        if ($user->site_admin) {
            return true;
        }
    }

    public function update(User $user, APIUser $api_user)
    {
        if ($user->site_admin) {
            return true;
        }
    }

    public function delete(User $user, APIUser $api_user)
    {
        if ($user->site_admin) {
            return true;
        }
    }
}

<?php

namespace App\Policies;

use App\User;
use App\APIUser;
use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Http\Request;

class APIUserPolicy
{
    use HandlesAuthorization;

    public function view_in_admin(User $user) {
        if ($user->site_admin) {
            return true;
        }
    }

    // Policy used for search -- available to all users.
    public function get_all(User $user)
    {
        return true;
    }

    public function get(User $user, APIUser $api_user)
    {
        if ($user->site_admin) {
            return true;
        }
    }

    public function create(User $user)
    {
        if ($user->site_admin) {
            return true;
        }
    }

    public function update(User $user, APIUser $api_user)
    {
        if ($user->site_admin) {
            return true;
        }
    }

    public function delete(User $user, APIUser $api_user)
    {
        if ($user->site_admin) {
            return true;
        }
    }
}

Change permissions for user search

Change permissions for user search


<?php

class CarouselSlide extends DataObject {
	private static $db = array(
		'Title' => 'Varchar(100)',
		'External' => 'Boolean',
		'ExternalLink' => 'Varchar(200)',
		'SlideSort' => 'Int'
	);

	private static $has_one = array(
		'SlideImage' => 'Image',
		'HolderPage' => 'Page',
		'IntenalLink' => 'SiteTree'
	);

	private static $default_sort = 'SlideSort';

	public function getCMSFields() {
		$fields = new FieldList();
		$fields->push(new TextField('Title', 'Title'));
		$fields->push(new UploadField('SlideImage', 'SlideImage'));
		$fields->push(new TreeDropdownField("IntenalLinkID", "Choose a page to link to", "SiteTree"));
		$fields->push(new CheckboxField('External', 'Using external link'));
		$fields->push(new TextField('ExternalLink', 'External Link URL'));

		return $fields;
	}
}

<?php

class CarouselSlide extends DataObject {
	private static $db = array(
		'Title' => 'Varchar(100)',
		'External' => 'Boolean',
		'ExternalLink' => 'Varchar(200)',
		'SlideSort' => 'Int'
	);

	private static $has_one = array(
		'SlideImage' => 'Image',
		'HolderPage' => 'Page',
		'IntenalLink' => 'SiteTree'
	);

	private static $default_sort = 'SlideSort';

	public function getCMSFields() {
		$fields = new FieldList();
		$fields->push(new TextField('Title', 'Title'));
		$fields->push($image = new UploadField('SlideImage', 'SlideImage'));
		$image->setAllowedFileCategories('image');
		$image->setAllowedMaxFileNumber(1);
		$image->setCanAttachExisting(true);
		$image->setFolderName('Carousel');

		$fields->push(new TreeDropdownField("IntenalLinkID", "Choose a page to link to", "SiteTree"));
		$fields->push(new CheckboxField('External', 'Using external link'));
		$fields->push(new TextField('ExternalLink', 'External Link URL'));

		return $fields;
	}
}

Add some sensible defaults to slide image upload field


<?php namespace Orchestra\Widget;

use Illuminate\Support\ServiceProvider;

class WidgetServiceProvider extends ServiceProvider {
	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app['orchestra.widget'] = $this->app->share(function()
		{
			return new Environment;
		});
	}

	/**
	 * Bootstrap the application events.
	 *
	 * @return void
	 */
	public function boot()
	{
		$this->package('orchestra/widget');
	}
}

<?php namespace Orchestra\Widget;

use Illuminate\Support\ServiceProvider;

class WidgetServiceProvider extends ServiceProvider {
	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		$this->app['orchestra.widget'] = $this->app->share(function()
		{
			return new Environment;
		});
	}

	/**
	 * Bootstrap the application events.
	 *
	 * @return void
	 */
	public function boot()
	{
		$this->package('orchestra/widget', 'orchestra/widget');
	}
}

Use proper namespace for package

Use proper namespace for package

Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>