<?php

namespace Frozzare\Tank;

use BadMethodCallException;

abstract class Service_Provider {

	/**
	 * The container.
	 *
	 * @var \Frozzare\Tank\Container
	 */
	protected $container;

	/**
	 * The constructor.
	 *
	 * @param \Frozzare\Tank\Container $container
	 */
	public function __construct( Container $container ) {
		$this->container = $container;
	}

	/**
	 * Registers service provider.
	 */
	abstract public function register();

	/**
	 * Dynamically handle missing method calls.
	 *
	 * @param  string $method
	 * @param  array  $parameters
	 *
	 * @throws \BadMethodCallException
	 *
	 * @return mixed
	 */
	public function __call( $method, $parameters ) {
		throw new BadMethodCallException( "Call to undefined method `{$method}`" );
	}
}

<?php

namespace Frozzare\Tank;

use BadMethodCallException;

abstract class Service_Provider {

	/**
	 * The container.
	 *
	 * @var \Frozzare\Tank\Container
	 */
	protected $container;

	/**
	 * The constructor.
	 *
	 * @param \Frozzare\Tank\Container $container
	 */
	public function __construct( Container $container ) {
		$this->container = $container;
	}

	/**
	 * Registers service provider.
	 */
	abstract public function register();

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

	/**
	 * Dynamically handle missing method calls.
	 *
	 * @param  string $method
	 * @param  array  $parameters
	 *
	 * @throws \BadMethodCallException
	 *
	 * @return mixed
	 */
	public function __call( $method, $parameters ) {
		throw new BadMethodCallException( "Call to undefined method `{$method}`" );
	}
}

Add provides method to service provider

Add provides method to service provider


<?php

namespace adLDAP\Classes;

use adLDAP\adLDAP;

/**
 * The base adLDAP class
 *
 * Class adLDAPBase
 * @package adLDAP\classes
 */
class adLDAPBase
{
    /**
     * The current adLDAP connection via dependency injection
     *
     * @var adLDAP
     */
    protected $adldap;

    /**
     * The current adLDAP connection
     *
     * @var \adLDAP\Interfaces\ConnectionInterface
     */
    protected $connection;

    /**
     * Constructor.
     *
     * @param adLDAP $adldap
     */
    public function __construct(adLDAP $adldap)
    {
        $this->adldap = $adldap;

        $this->connection = $adldap->getLdapConnection();
    }
}

<?php

namespace adLDAP\Classes;

use adLDAP\adLDAP;

/**
 * The base adLDAP class
 *
 * Class adLDAPBase
 * @package adLDAP\classes
 */
class adLDAPBase
{
    /**
     * The current adLDAP connection via dependency injection
     *
     * @var adLDAP
     */
    protected $adldap;

    /**
     * The current adLDAP connection
     *
     * @var \adLDAP\Interfaces\ConnectionInterface
     */
    protected $connection;

    /**
     * Constructor.
     *
     * @param adLDAP $adldap
     */
    public function __construct(adLDAP $adldap)
    {
        $this->adldap = $adldap;

        $connection = $adldap->getLdapConnection();

        if($connection) $this->connection = $connection;
    }
}

Make sure the connection exists before setting it


<?php namespace Picqer\Financials\Exact\Query;

class Resultset
{
    protected $connection;

    protected $url;

    protected $class;

    protected $params;

    public function __construct($connection, $url, $class, $params)
    {
        $this->connection = $connection;
        $this->url = $url;
        $this->class = $class;
        $this->params = $params;
    }

    public function next()
    {
        $result = $this->connection->get($this->url, $this->params);
        $this->url = $this->connection->nextUrl;
        return $this->collectionFromResult($result, $this->class);
    }

    public function hasMore()
    {
        return $this->url !== null;
    }

    protected function collectionFromResult($result)
    {
        // If we have one result which is not an assoc array, make it the first element of an array for the
        // collectionFromResult function so we always return a collection from filter
        if ((bool) count(array_filter(array_keys($result), 'is_string'))) {
            $result = [ $result ];
        }

        $class = $this->class;
        $collection = [];

        foreach ($result as $r) {
            $collection[] = new $class($this->connection, $r);
        }

        return $collection;
    }
}

<?php namespace Picqer\Financials\Exact\Query;

class Resultset
{
    protected $connection;

    protected $url;

    protected $class;

    protected $params;

    public function __construct($connection, $url, $class, $params)
    {
        $this->connection = $connection;
        $this->url = $url;
        $this->class = $class;
        $this->params = $params;
    }

    public function next()
    {
        $result = $this->connection->get($this->url, $this->params);
        $this->url = $this->connection->nextUrl;
        $this->params = null;
        return $this->collectionFromResult($result, $this->class);
    }

    public function hasMore()
    {
        return $this->url !== null;
    }

    protected function collectionFromResult($result)
    {
        // If we have one result which is not an assoc array, make it the first element of an array for the
        // collectionFromResult function so we always return a collection from filter
        if ((bool) count(array_filter(array_keys($result), 'is_string'))) {
            $result = [ $result ];
        }

        $class = $this->class;
        $collection = [];

        foreach ($result as $r) {
            $collection[] = new $class($this->connection, $r);
        }

        return $collection;
    }
}

Reset params and next api call

Reset params and next api call


<?php

/**
 * @author Shiplu Mokaddim <shiplu@mokadd.im>
 * @copyright 2012 Shiplu Mokaddim
 * @package Biriani
 */

/**
 * class IExtractableBiriani
 */
interface IExtractable {

    /**
     * @return array extracted data in an associative array
     * @abstract
     * @access public
     */
    public function extract();

    /**
     * Checks if any http response can be extracted.
     * @return boolean true if it can extract the provided response certainly
     * @param $response Biriani_Response Http response to check
     */
    public static function can_extract(Biriani_Response $response);

}

?>

<?php

/**
 * @author Shiplu Mokaddim <shiplu@mokadd.im>
 * @copyright 2012 Shiplu Mokaddim
 * @package Biriani
 */

/**
 * class IExtractableBiriani
 */
interface IExtractable {

    /**
     * @return array extracted data in an associative array
     * @abstract
     * @access public
     * @return Biriani_Data
     */
    public function extract();

    /**
     * Checks if any http response can be extracted.
     * @return boolean true if it can extract the provided response certainly
     * @param $response Biriani_Response Http response to check
     */
    public static function can_extract(Biriani_Response $response);

}

?>

Return type of extract() function added

Return type of extract() function added


<?php

namespace Laravel\Lumen\Http;

use Illuminate\Support\Arr;
use Illuminate\Http\Request as BaseRequest;

class Request extends BaseRequest
{
    /**
     * Get the route handling the request.
     *
     * @param  string|null  $param
     * @param  mixed  $default
     *
     * @return array|string
     */
    public function route($param = null, $default = null)
    {
        $route = call_user_func($this->getRouteResolver());

        if (is_null($route) || is_null($param)) {
            return $route;
        }

        return Arr::get($route[2], $param, $default);
    }
}

<?php

namespace Laravel\Lumen\Http;

use Illuminate\Support\Arr;
use Illuminate\Http\Request as BaseRequest;

class Request extends BaseRequest
{
    /**
     * Determine if the given offset exists.
     *
     * @param  string  $offset
     * @return bool
     */
    public function offsetExists($offset)
    {
        return Arr::has(
            $this->all() + $this->route()[2],
            $offset
        );
    }

    /**
     * Get the route handling the request.
     *
     * @param  string|null  $param
     * @param  mixed  $default
     *
     * @return array|string
     */
    public function route($param = null, $default = null)
    {
        $route = call_user_func($this->getRouteResolver());

        if (is_null($route) || is_null($param)) {
            return $route;
        }

        return Arr::get($route[2], $param, $default);
    }
}

Make the "offsetExists" method compatible with Lumen.


<?php

namespace BNETDocs\Libraries;

use \BNETDocs\Libraries\Authentication;
use \BNETDocs\Libraries\EventTypes;
use \BNETDocs\Libraries\Logger;

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

class BlizzardChecker {

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

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

  public static function logIfBlizzard() {
    $user_id = (
      isset(Authentication::$user) ? Authentication::$user->getId() : null
    );
    if (self::checkIfBlizzard()) {
      Logger::logEvent(
        EventTypes::BLIZZARD_VISIT,
        $user_id,
        getenv('REMOTE_ADDR'),
        json_encode([
          'method'  => getenv('REQUEST_METHOD'),
          'referer' => getenv('HTTP_REFERER'),
          'uri'     => getenv('REQUEST_URI'),
          'version' => VersionInfo::get(),
        ])
      );
    }
  }

}

<?php

namespace BNETDocs\Libraries;

use \BNETDocs\Libraries\Authentication;
use \BNETDocs\Libraries\EventTypes;
use \BNETDocs\Libraries\Logger;

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

class BlizzardChecker {

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

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

  public static function logIfBlizzard() {
    $user_id = (
      isset(Authentication::$user) ? Authentication::$user->getId() : null
    );
    if (self::checkIfBlizzard()) {
      Logger::logEvent(
        EventTypes::BLIZZARD_VISIT,
        $user_id,
        getenv('REMOTE_ADDR'),
        json_encode([
          'method'     => getenv('REQUEST_METHOD'),
          'referer'    => getenv('HTTP_REFERER'),
          'uri'        => getenv('REQUEST_URI'),
          'user_agent' => getenv('HTTP_USER_AGENT'),
          'version'    => VersionInfo::get(),
        ])
      );
    }
  }

}

Add user agent to Blizzard visit log

Add user agent to Blizzard visit log


<?php

namespace Oro\Bundle\InstallerBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

use Oro\Bundle\InstallerBundle\CommandExecutor;

class PlatformUpdateCommand extends ContainerAwareCommand
{
    /**
     * @inheritdoc
     */
    protected function configure()
    {
        $this->setName('oro:platform:update')
            ->setDescription('Execute platform update commands.');
    }

    /**
     * @inheritdoc
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $commandExecutor = new CommandExecutor(
            $input->hasOption('env') ? $input->getOption('env') : null,
            $output,
            $this->getApplication()
        );
        $commandExecutor
            ->runCommand('oro:entity-config:update')
            ->runCommand('oro:entity-extend:update')
            ->runCommand('oro:navigation:init')
            ->runCommand('assets:install')
            ->runCommand('assetic:dump')
            ->runCommand('fos:js-routing:dump', array('--target' => 'js/routes.js'))
            ->runCommand('oro:localization:dump')
            ->runCommand('oro:translation:dump')
            ->runCommand('oro:requirejs:build');
    }
}

<?php

namespace Oro\Bundle\InstallerBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

use Oro\Bundle\InstallerBundle\CommandExecutor;

class PlatformUpdateCommand extends ContainerAwareCommand
{
    /**
     * @inheritdoc
     */
    protected function configure()
    {
        $this->setName('oro:platform:update')
            ->setDescription('Execute platform update commands.');
    }

    /**
     * @inheritdoc
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $commandExecutor = new CommandExecutor(
            $input->hasOption('env') ? $input->getOption('env') : null,
            $output,
            $this->getApplication()
        );
        $commandExecutor
            ->runCommand('oro:entity-config:update')
            ->runCommand('oro:entity-extend:update')
            ->runCommand('oro:navigation:init')
            ->runCommand('assets:install')
            ->runCommand('assetic:dump')
            ->runCommand('fos:js-routing:dump', array('--target' => 'web/js/routes.js'))
            ->runCommand('oro:localization:dump')
            ->runCommand('oro:translation:dump')
            ->runCommand('oro:requirejs:build');
    }
}

BAP-2667: Modify CLI installer to allow run common commands from Package Manager[


<?php

namespace Override\FosUserBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use FOS\UserBundle\Controller\RegistrationController as BaseController;

class RegistrationController extends BaseController
{

    public function registerAction(Request $request)
    {
        $securityService = $this->container->get('security.context');
        if ($securityService->isGranted('ROLE_SECRETARY') ||
            $securityService->isGranted('ROLE_ADMIN'))
        {

            return parent::registerAction($request);
        }
        return parent::registerAction($request);
        //throw new \Exception();
    }
}

<?php

namespace Override\FosUserBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use FOS\UserBundle\Controller\RegistrationController as BaseController;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\Event\UserEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;

class RegistrationController extends BaseController
{

    public function registerAction(Request $request)
    {
        $securityService = $this->container->get('security.context');
        if ($securityService->isGranted('ROLE_SECRETARY') ||
            $securityService->isGranted('ROLE_ADMIN'))
        {
            /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
            $formFactory = $this->container->get('fos_user.registration.form.factory');
            /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
            $userManager = $this->container->get('fos_user.user_manager');
            /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
            $dispatcher = $this->container->get('event_dispatcher');

            $user = $userManager->createUser();
            $user->setEnabled(true);
            $user->setRoles(array('ROLE_STUDENT'));

            $event = new GetResponseUserEvent($user, $request);
            $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);

            if (null !== $event->getResponse()) {
                return $event->getResponse();
            }

            $form = $formFactory->createForm();
            $form->setData($user);

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

                if ($form->isValid()) {
                    $event = new FormEvent($form, $request);
                    $dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);

                    $userManager->updateUser($user);

                    if (null === $response = $event->getResponse()) {
                        $url = $this->container->get('router')->generate('fos_user_registration_confirmed');
                        $response = new RedirectResponse($url);
                    }

                    return $response;
                }
            }

            return $this->container->get('templating')->renderResponse('FOSUserBundle:Registration:register.html.'.$this->getEngine(), array(
                'form' => $form->createView(),
            ));
        }
        return parent::registerAction($request);
        //throw new \Exception();
    }
}

Change behavior when adding an user and set default role as student


<?php
/*
 * This file is part of the prooph software processing toolbox.
 * (c) prooph software GmbH <contact@prooph.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * Date: 30.01.15 - 08:19
 */

namespace Prooph\Done\Process\Functional\Iterator;

/**
 * Class MapIterator
 *
 * @package Prooph\Done\Process\Functional\Iterator
 * @author Alexander Miertsch <kontakt@codeliner.ws>
 */
final class MapIterator extends \IteratorIterator
{
    /**
     * @var callable
     */
    protected $callback;

    public function __construct(\Traversable $iterator, $callback)
    {
        if (!is_callable($callback)) {
            throw new \InvalidArgumentException("Provided callback should be callable. Got " . gettype($callback));
        }
        parent::__construct($iterator);
        $this->callback = $callback;
    }

    public function current()
    {
        $iterator = $this->getInnerIterator();

        $callback = $this->callback;

        return $callback(parent::current(), parent::key(), $iterator);
    }
}

<?php
/*
 * This file is part of the prooph software processing toolbox.
 * (c) prooph software GmbH <contact@prooph.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * Date: 30.01.15 - 08:19
 */

namespace Prooph\Done\Process\Functional\Iterator;

/**
 * Class MapIterator
 *
 * @package Prooph\Done\Process\Functional\Iterator
 * @author Alexander Miertsch <kontakt@codeliner.ws>
 */
final class MapIterator extends \IteratorIterator
{
    /**
     * @var callable
     */
    protected $callback;

    public function __construct(\Traversable $iterator, callable $callback)
    {
        parent::__construct($iterator);
        $this->callback = $callback;
    }

    public function current()
    {
        $iterator = $this->getInnerIterator();

        $callback = $this->callback;

        return $callback(parent::current(), parent::key(), $iterator);
    }
}

Use PHP callable for argument specification.


<?php

/**
 * Neo Framework
 *
 * @link https://neo-framework.github.io
 * @copyright Copyright (c) 2016-2017 YouniS Bensalah <younis.bensalah@gmail.com>
 * @license MIT
 */

namespace neo\controller;

use \Klein\Request;
use \Klein\Response;
use \endobox\Factory as Endobox;

abstract class Controller
{

    protected $request;

    protected $response;

    protected $view;

    public function __construct(Request $request, Response $response, Endobox $endobox)
    {
        $this->request = $request;
        $this->response = $response;
        $this->view = $endobox;
    }

}

<?php

/**
 * Neo Framework
 *
 * @link https://neo-framework.github.io
 * @copyright Copyright (c) 2016-2017 YouniS Bensalah <younis.bensalah@gmail.com>
 * @license MIT
 */

namespace neo\controller;

use \Klein\Request;
use \Klein\Response;
use \endobox\Factory as Endobox;
use \endobox\Box;

abstract class Controller
{

    protected $request;

    protected $response;

    protected $view;

    public function __construct(Request $request, Response $response, Endobox $endobox)
    {
        $this->request = $request;
        $this->response = $response;
        $this->view = $endobox;
    }

    /**
     * Usually, this is what I want to do:
     *
     * $test = $endobox('mytemplate');
     *
     * Now, $endobox is no longer a simple variable, but a property:
     *
     * $test = $this->view('mytemplate');
     *
     * Except PHP will now think that we're trying to call a method named view() which does not exist.
     * To fix this we'd have to write explicit parenthesis like this:
     *
     * $test = ($this->view)('mytemplate');
     *
     * But that's pretty ugly and that's why this method exists.
     */
     public function view(string $template) : Box
     {
         return ($this->view)($template);
     }

}

Add view() hack thx @fwhcat lol

Add view() hack thx @fwhcat lol


<?php
namespace Saft\Data;

/**
 * @note We have to decide how the ParserInterface should be implemented. One option
 * could be that a parser can accept multiple files/streams which are handled as one
 * graph and all statements are combined in the resulting StatementIterator.
 */
interface ParserInterface
{
    /**
     * Maybe the PHP Stream API will be relevant here:
     * http://php.net/manual/en/book.stream.php
     * @unstable
     * @return \Saft\Rdf\StatementIterator a StatementIterator containing all the Statements parsed by the parser to far
     */
    public function parseStreamToIterator($inputStream, $baseUri);

    /**
     * @return array with a prefix mapping of the prefixes parsed so far
     */
    public function getCurrentPrefixlist();
}

<?php
namespace Saft\Data;

/**
 * @note We have to decide how the ParserInterface should be implemented. One option
 * could be that a parser can accept multiple files/streams which are handled as one
 * graph and all statements are combined in the resulting StatementIterator.
 */
interface ParserInterface
{
    /**
     * Maybe the PHP Stream API will be relevant here:
     * http://php.net/manual/en/book.stream.php
     * @unstable
     * @param $inputStream string filename of the stream to parse {@url http://php.net/manual/en/book.stream.php}
     * @param $baseUri string the base URI of the parsed content. If this URI is null the inputStreams URL is taken as
     *                        base URI. (If the base URI is no valid URI an Exception will be thrown.)
     * @param $serialization string the serialization of the inputStream. If null is given the parser will either apply
     *                              some standard serialization, or the only one it is supporting, or will try to guess
     *                              the correct serialization, or will throw an Exception.
     * @return \Saft\Rdf\StatementIterator a StatementIterator containing all the Statements parsed by the parser to far
     */
    public function parseStreamToIterator($inputStream, $baseUri = null, $serialization = null);

    /**
     * @unstable
     * @return array An associative array with a prefix mapping of the prefixes parsed so far. The key will be the
     *               prefix, while the values contains the according namespace URI.
     */
    public function getCurrentPrefixList();

    /**
     * @unstable
     * @return array of supported mimetypes which are understood by this parser
     */
    public function getSupportedSerializations();
}

Update documentation for parser interface


<?php
namespace Neos\Flow\Tests\Unit\Http\Helper;

use GuzzleHttp\Psr7\ServerRequest;
use Neos\Flow\Http\Helper\RequestInformationHelper;
use Neos\Flow\Tests\UnitTestCase;

/**
 * Tests for the RequestInformationHelper
 */
class RequestInformationHelperTest extends UnitTestCase
{
    /**
     * @test
     */
    public function renderRequestHeadersWillNotDiscloseAuthorizationCredentials()
    {
        $request = ServerRequest::fromGlobals()
            ->withAddedHeader('Authorization', 'Basic SomeUser:SomePassword')
            ->withAddedHeader('Authorization', 'Bearer SomeToken');

        $renderedHeaders = RequestInformationHelper::renderRequestHeaders($request);
        self::assertStringContainsString('SomePassword', $renderedHeaders);
        self::assertStringContainsString('SomeToken', $renderedHeaders);
    }
}

<?php
namespace Neos\Flow\Tests\Unit\Http\Helper;

use GuzzleHttp\Psr7\ServerRequest;
use Neos\Flow\Http\Helper\RequestInformationHelper;
use Neos\Flow\Tests\UnitTestCase;

/**
 * Tests for the RequestInformationHelper
 */
class RequestInformationHelperTest extends UnitTestCase
{
    /**
     * @test
     */
    public function renderRequestHeadersWillNotDiscloseAuthorizationCredentials()
    {
        $request = ServerRequest::fromGlobals()
            ->withAddedHeader('Authorization', 'Basic SomeUser:SomePassword')
            ->withAddedHeader('Authorization', 'Bearer SomeToken');

        $renderedHeaders = RequestInformationHelper::renderRequestHeaders($request);
        self::assertStringNotContainsString('SomePassword', $renderedHeaders);
        self::assertStringNotContainsString('SomeToken', $renderedHeaders);
    }
}

Adjust test assertions to PHPUnit 8

TASK: Adjust test assertions to PHPUnit 8


<?php namespace App\Http\Middleware;

use Closure;

class Secure
{

	/**
	 * Handle an incoming request.
	 *
	 * @param  \Illuminate\Http\Request $request
	 * @param  \Closure $next
	 * @return mixed
	 */
	public function handle($request, Closure $next)
	{
		if (!$request->secure())
		{
			return redirect()->secure($request->getRequestUri());
		}

		return $next($request);
	}

}

<?php namespace App\Http\Middleware;

use Closure;

class Secure
{

	/**
	 * Handle an incoming request.
	 *
	 * @param  \Illuminate\Http\Request $request
	 * @param  \Closure $next
	 * @return mixed
	 */
	public function handle($request, Closure $next)
	{
		// see http://stackoverflow.com/a/25095936
		if (!($request->header('x-forwarded-proto') <> 'https'))
		{
			return redirect()->secure($request->getRequestUri());
		}

		return $next($request);
	}

}

Use heroku variable for ssl instead of default Laravel's.


<?php

namespace App\Models\Dsc;

use App\Models\DscModel;
use App\Models\ElasticSearchable;

/**
 * Represents an overall digital publication.
 */
class Publication extends DscModel
{

    use ElasticSearchable;

    public function sections()
    {
        return $this->hasMany('App\Models\Dsc\Section');
    }

    public function getGenericPageId()
    {
        switch ($this->id) {
            case 7:
                return 9;
            break;
            case 12:
                return 6;
            break;
            case 135446:
                return 12;
            break;
            case 141096:
                return 7;
            break;
            case 135466:
                return 11;
            break;
            case 406:
                return 13;
            break;
            case 445:
                return 8;
            break;
            case 480:
                return 5;
            break;
            case 226:
                return 10;
            break;
            case 140019:
                return 4;
            break;
        }
    }
}

<?php

namespace App\Models\Dsc;

use App\Models\DscModel;
use App\Models\ElasticSearchable;

/**
 * Represents an overall digital publication.
 */
class Publication extends DscModel
{

    use ElasticSearchable;

    private static $genericPageIds = [
        7 => 9,
        12 => 6,
        135446 => 12,
        141096 => 7,
        135466 => 11,
        406 => 13,
        445 => 8,
        480 => 5,
        226 => 10,
        140019 => 4,
    ];

    public function sections()
    {
        return $this->hasMany('App\Models\Dsc\Section');
    }

    /**
     * WEB-35, API-332: Each publication is represented by a generic
     * page on our website, which links to that publication.
     */
    public function getGenericPageId()
    {
        return self::$genericPageIds[$this->id] ?? null;
    }
}

Clarify `getGenericPageId` with a comment [API-332]


<?php
/**
 * @project Trinity Framework
 * @copyright Copyright (c) 2017-2017 nephp. (https://github.com/nephp)
 */

namespace App\r7r1n17y\Framework;

/**
 * @name ExtensionBridge
 */
abstract class ExtensionBridge {

    /**
     * @var _exts Container for each object
     * @type private
     */
    private $_exts = array();

    /**
     * @var _this Used to call custom methods/func
     * @type public
     */
    public $_this;

    function __construct(){$_this = $this;}

    public function addExt($object)
    {
        $this->_exts[]=$object;
    }

    public function __get($varname)
    {
        foreach($this->_exts as $ext)
        {
            if(property_exists($ext,$varname))
            return $ext->$varname;
        }
    }

    public function __call($method,$args)
    {
        foreach($this->_exts as $ext)
        {
            if(method_exists($ext,$method))
            return call_user_method_array($method,$ext,$args);
        }
        throw new Exception("This Method {$method} doesn't exists");
    }

}

Add the Extension Bride class and added some comments


<?php

namespace Spy\Timeline\ResolveComponent;

use Spy\Timeline\Exception\ResolveComponentDataException;
use Spy\Timeline\ResolveComponent\ValueObject\ResolveComponentModelIdentifier;
use Spy\Timeline\ResolveComponent\ValueObject\ResolvedComponentData;

/**
 * Basic implementation of a component data resolver.
 *
 * When no object is given we use the given model and identifier and data=null as ResolvedComponentData arguments
 *
 * When an object is given
 *  - the model string is extracted by using get_class on the model
 *  - The identifier is extracted by using the getId method on the model
 *
 * When not able to resolve the component data an
 * Spy\Timeline\Exception\ResolveComponentDataException exception is thrown.
 */
class BasicComponentDataResolver implements ComponentDataResolverInterface
{
    /**
     * {@inheritdoc}
     */
    public function resolveComponentData(ResolveComponentModelIdentifier $resolve)
    {
        $model = $resolve->getModel();
        $identifier = $resolve->getIdentifier();

        $data = null;
        if (is_object($model)) {
            $data = $model;
            $modelClass = get_class($model);

            if (!method_exists($model, 'getId')) {
                throw new ResolveComponentDataException('Model must have a getId method');
            }

            $identifier = $model->getId();
            $model = $modelClass;
        }

        return new ResolvedComponentData($model, $identifier, $data);
    }
}

<?php

namespace Spy\Timeline\ResolveComponent;

use Doctrine\Common\Util\ClassUtils;
use Spy\Timeline\Exception\ResolveComponentDataException;
use Spy\Timeline\ResolveComponent\ValueObject\ResolveComponentModelIdentifier;
use Spy\Timeline\ResolveComponent\ValueObject\ResolvedComponentData;

/**
 * Basic implementation of a component data resolver.
 *
 * When no object is given we use the given model and identifier and data=null as ResolvedComponentData arguments
 *
 * When an object is given
 *  - the model string is extracted by using get_class on the model
 *  - The identifier is extracted by using the getId method on the model
 *
 * When not able to resolve the component data an
 * Spy\Timeline\Exception\ResolveComponentDataException exception is thrown.
 */
class BasicComponentDataResolver implements ComponentDataResolverInterface
{
    /**
     * {@inheritdoc}
     */
    public function resolveComponentData(ResolveComponentModelIdentifier $resolve)
    {
        $model = $resolve->getModel();
        $identifier = $resolve->getIdentifier();

        $data = null;
        if (is_object($model)) {
            $data = $model;
            $modelClass = ClassUtils::getRealClass(get_class($model));

            if (!method_exists($model, 'getId')) {
                throw new ResolveComponentDataException('Model must have a getId method');
            }

            $identifier = $model->getId();
            $model = $modelClass;
        }

        return new ResolvedComponentData($model, $identifier, $data);
    }
}

Resolve Doctrine proxies to real entity names in order to generate proper
identifiers for model.

| Q             | A
| ------------- | ---
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| License       | MIT


<?php

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

class CreateUserTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('user', function(Blueprint $table) {
			$table->increments('id');
            $table->string('email');
            $table->string('firstname');
			$table->string('lastname');
			$table->string('goggle_accesstoken');
			$table->boolean('is_admin');
            $table->softDeletes();
            $table->timestamps();
		});
	}

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

}

<?php

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

class CreateUserTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('users', function(Blueprint $table) {
			$table->increments('id');
            $table->string('email')->unique();
            $table->string('firstname');
			$table->string('lastname');
			$table->string('google_accesstoken');
			$table->boolean('is_admin')->default(0);
            $table->softDeletes();
            $table->timestamps();
		});
	}

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

}

Update the migration with the right user table name and defaults


<?php
namespace TYPO3\Fluid\ViewHelpers;

/*                                                                        *
 * This script belongs to the FLOW3 package "Fluid".                      *
 *                                                                        *
 * It is free software; you can redistribute it and/or modify it under    *
 * the terms of the GNU Lesser General Public License, either version 3   *
 *  of the License, or (at your option) any later version.                *
 *                                                                        *
 * The TYPO3 project - inspiring people to share!                         *
 *                                                                        */

/**
 * View helper which creates a <base href="..."></base> tag. The Base URI
 * is taken from the current request.
 * In FLOW3, you should always include this ViewHelper to make the links work.
 *
 * = Examples =
 *
 * <code title="Example">
 * <f:base />
 * </code>
 * <output>
 * <base href="http://yourdomain.tld/" />
 * (depending on your domain)
 * </output>
 *
 * @api
 */
class BaseViewHelper extends \TYPO3\Fluid\Core\ViewHelper\AbstractViewHelper {

	/**
	 * Render the "Base" tag by outputting $request->getBaseUri()
	 *
	 * @return string "base"-Tag.
	 * @api
	 */
	public function render() {
		return '<base href="' . $this->controllerContext->getRequest()->getHttpRequest()->getBaseUri() . '" />';
	}
}

?>

<?php
namespace TYPO3\Fluid\ViewHelpers;

/*                                                                        *
 * This script belongs to the FLOW3 package "Fluid".                      *
 *                                                                        *
 * It is free software; you can redistribute it and/or modify it under    *
 * the terms of the GNU Lesser General Public License, either version 3   *
 *  of the License, or (at your option) any later version.                *
 *                                                                        *
 * The TYPO3 project - inspiring people to share!                         *
 *                                                                        */

/**
 * View helper which creates a <base href="..."></base> tag. The Base URI
 * is taken from the current request.
 * In FLOW3, you should always include this ViewHelper to make the links work.
 *
 * = Examples =
 *
 * <code title="Example">
 * <f:base />
 * </code>
 * <output>
 * <base href="http://yourdomain.tld/" />
 * (depending on your domain)
 * </output>
 *
 * @api
 */
class BaseViewHelper extends \TYPO3\Fluid\Core\ViewHelper\AbstractViewHelper {

	/**
	 * Render the "Base" tag by outputting $httpRequest->getBaseUri()
	 *
	 * @return string "base"-Tag.
	 * @api
	 */
	public function render() {
		return '<base href="' . $this->controllerContext->getRequest()->getHttpRequest()->getBaseUri() . '" />';
	}
}

?>

Adjust a comment to HTTP foundation

[TASK] Adjust a comment to HTTP foundation

Change-Id: I92e60d98528c1fd0cbdf0eeb08466e77014bc780
Related: #35243
Releases: 1.1
Original-Commit-Hash: 0914e9da46c731746fc71a871c363cc00be16e62


<?php
/**
 * @package Core
 * @subpackage model.interfaces
 */
interface IIndexable extends IBaseObject
{
	const FIELD_TYPE_STRING = 'string';
	const FIELD_TYPE_INTEGER = 'int';
	const FIELD_TYPE_DATETIME = 'datetime';

	/**
	 * Is the id as used and know by Kaltura
	 * @return string
	 */
	public function getId();

	/**
	 * Is the id as used and know by the indexing server
	 * @return int
	 */
	public function getIntId();

	/**
	 * @return string
	 */
	public function getEntryId();

	/**
	 * @return string object propel name
	 */
	public function getObjectIndexName();

	/**
	 * @return array while the key is the index attribute name and the value is the getter name
	 * For example array('name' => 'title') if name should be retrieved by getTitle() getter
	 */
	public function getIndexFieldsMap();

	/**
	 * @return string field type, string, int or timestamp
	 */
	public function getIndexFieldType($field);
}

<?php
/**
 * @package Core
 * @subpackage model.interfaces
 */
interface IIndexable extends IBaseObject
{
	const FIELD_TYPE_STRING = 'string';
	const FIELD_TYPE_INTEGER = 'int';
	const FIELD_TYPE_DATETIME = 'datetime';

	/**
	 * Is the id as used and know by Kaltura
	 * @return string
	 */
	public function getId();

	/**
	 * Is the id as used and know by the indexing server
	 * @return int
	 */
	public function getIntId();

	/**
	 * @return string
	 */
	public function getEntryId();

	/**
	 * @return string object propel name
	 */
	public function getObjectIndexName();

	/**
	 * @return array while the key is the index attribute name and the value is the getter name
	 * For example array('name' => 'title') if name should be retrieved by getTitle() getter
	 */
	public function getIndexFieldsMap();

	/**
	 * @return string field type, string, int or timestamp
	 */
	public function getIndexFieldType($field);

	/**
	 * @param int $time
	 * @return IIndexable
	 */
	public function setUpdatedAt($time);

	/**
	 * @param PropelPDO $con
	 * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations.
	 * @throws PropelException
	 */
	public function save(PropelPDO $con = null);
}

Update entry updated at field

Update entry updated at field

git-svn-id: 8a2ccb88241e16c78017770bc38d91d6d5396a5a@57660 6b8eccd3-e8c5-4e7d-8186-e12b5326b719


<?php

namespace Surfnet\StepupMiddleware\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20160622160146 extends AbstractMigration
{
    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('CREATE TABLE institution_with_ra_locations (institution VARCHAR(255) NOT NULL, PRIMARY KEY(institution)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
        $this->addSql('DROP TABLE institution_with_ra_locations');
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('CREATE TABLE institution_with_ra_locations (institution VARCHAR(255) NOT NULL COLLATE utf8_unicode_ci, PRIMARY KEY(institution)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
        $this->addSql('DROP TABLE institution_with_ra_locations');
    }
}

<?php

namespace Surfnet\StepupMiddleware\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20160622160146 extends AbstractMigration
{
    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('CREATE TABLE institution_with_ra_locations (institution VARCHAR(255) NOT NULL, PRIMARY KEY(institution)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
        $this->addSql('DROP TABLE institution_with_personal_ra_details');
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('CREATE TABLE institution_with_ra_locations (institution VARCHAR(255) NOT NULL COLLATE utf8_unicode_ci, PRIMARY KEY(institution)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
        $this->addSql('DROP TABLE institution_with_personal_ra_details');
    }
}

Correct table names in migration

Correct table names in migration


<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Illuminate\Http\Request;

class NotificationsController extends Controller {

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{
		//
	}

	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create()
	{
		//
	}

	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
		//
	}

	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		//
	}

	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		//
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		//
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		//
	}

}

<?php namespace App\Http\Controllers;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Notification;
use Illuminate\Http\Request;

class NotificationsController extends Controller {

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{
		$notifications = Auth::user()->notifications()->paginate(15);

        Auth::user()->notifications_count = 0;
        Auth::user()->save();

        return view('notifications.index', compact('notifications'));
	}

	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		Notification::destroy($id);

        return redirect()->route('notifications.index');
	}

}

Add the method to show all the notifications.


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

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        $this->layout('layout/layout_home');

        return new ViewModel();
    }

    public function registerAction()
    {
        return new ViewModel();
    }

    public function venueAction()
    {
        return new ViewModel();
    }

    public function privacyAction()
    {
        return new ViewModel();
    }

    public function diversityAction()
    {
        return new ViewModel();
    }

    public function conductAction()
    {
        return new ViewModel();
    }

    public function aboutAction()
    {
        return new ViewModel();
    }

    public function eventsAction()
    {
        return new ViewModel();
    }

    public function unconAction()
    {
        return new ViewModel();
    }

    public function sitemapAction()
    {
        $this->layout('layout/xml');
    }
}

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

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        $this->layout('layout/layout_home');

        return new ViewModel();
    }

    public function registerAction()
    {
        return new ViewModel();
    }

    public function venueAction()
    {
        return new ViewModel();
    }

    public function privacyAction()
    {
        return new ViewModel();
    }

    public function diversityAction()
    {
        return new ViewModel();
    }

    public function conductAction()
    {
        return new ViewModel();
    }

    public function expectAction()
    {
        return new ViewModel();
    }

    public function aboutAction()
    {
        return new ViewModel();
    }

    public function eventsAction()
    {
        return new ViewModel();
    }

    public function unconAction()
    {
        return new ViewModel();
    }

    public function sitemapAction()
    {
        $this->layout('layout/xml');
    }
}

Add action for possible future content

Add  action for possible future content


<?php

namespace Tests\FileNamingResolver\NamingStrategy;

use FileNamingResolver\FileInfo;
use FileNamingResolver\NamingStrategy\CallbackNamingStrategy;

/**
 * @author Victor Bocharsky <bocharsky.bw@gmail.com>
 */
class CallbackNamingStrategyTest extends \PHPUnit_Framework_TestCase
{
    public function testGetFunc()
    {
        $func = function(FileInfo $fileInfo) {
            return $fileInfo->toString();
        };
        $strategy = new CallbackNamingStrategy($func);

        $this->assertSame($func, $strategy->getCallback());
    }
}

<?php

namespace Tests\FileNamingResolver\NamingStrategy;

use FileNamingResolver\FileInfo;
use FileNamingResolver\NamingStrategy\CallbackNamingStrategy;

/**
 * @author Victor Bocharsky <bocharsky.bw@gmail.com>
 */
class CallbackNamingStrategyTest extends \PHPUnit_Framework_TestCase
{
    public function testProvideName()
    {
        $strategy = new CallbackNamingStrategy(function(FileInfo $srcFileInfo) {
            return $srcFileInfo
                ->changePath($srcFileInfo->getPath().'/dir1')
                ->changeBasename('file1')
            ;
        });
        $srcFileInfo = new FileInfo('/dir/file.ext');
        $dstFileInfo = $strategy->provideName($srcFileInfo);
        $this->assertInstanceOf('FileNamingResolver\FileInfo', $dstFileInfo);
        $this->assertEquals('/dir/dir1/file1.ext', $dstFileInfo->toString());
    }

    /**
     * @expectedException \RuntimeException
     */
    public function testProvideNameException()
    {
        $strategy = new CallbackNamingStrategy(function(FileInfo $fileInfo) {
            return $fileInfo->toString();
        });
        $srcFileInfo = new FileInfo(__FILE__);
        $strategy->provideName($srcFileInfo);
    }

    public function testGetFunc()
    {
        $func = function(FileInfo $fileInfo) {
            return $fileInfo->toString();
        };
        $strategy = new CallbackNamingStrategy($func);

        $this->assertSame($func, $strategy->getCallback());
    }
}

Cover exception throwing in the CallbackNamingStrategy


<?php

namespace SitemapPlugin\Model;

/**
 * @author Arkadiusz Krakowiak <arkadiusz.krakowiak@lakion.com>
 */
interface SitemapUrlInterface
{
    /**
     * @return string
     */
    public function getLocalization();

    /**
     * @param string $localization
     */
    public function setLocalization($localization);

    /**
     * @return \DateTime
     */
    public function getLastModification();

    /**
     * @param \DateTime $lastModification
     */
    public function setLastModification(\DateTime $lastModification);

    /**
     * @return string
     */
    public function getChangeFrequency();

    /**
     * @param ChangeFrequency $changeFrequency
     */
    public function setChangeFrequency(ChangeFrequency $changeFrequency);

    /**
     * @return float
     */
    public function getPriority();

    /**
     * @param float $priority
     */
    public function setPriority($priority);
}

<?php

namespace SitemapPlugin\Model;

/**
 * @author Arkadiusz Krakowiak <arkadiusz.krakowiak@lakion.com>
 */
interface SitemapUrlInterface
{
    /**
     * @return string
     */
    public function getLocalization();

    /**
     * @param string $localization
     */
    public function setLocalization($localization);

    /**
     * {@inheritdoc}
     */
    public function addAlternative($location, $locale);

    /**
     * {@inheritdoc}
     */
    public function setAlternatives(array $alternatives);

    /**
     * {@inheritdoc}
     */
    public function getAlternatives();

    /**
     * @return \DateTime
     */
    public function getLastModification();

    /**
     * @param \DateTime $lastModification
     */
    public function setLastModification(\DateTime $lastModification);

    /**
     * @return string
     */
    public function getChangeFrequency();

    /**
     * @param ChangeFrequency $changeFrequency
     */
    public function setChangeFrequency(ChangeFrequency $changeFrequency);

    /**
     * @return float
     */
    public function getPriority();

    /**
     * @param float $priority
     */
    public function setPriority($priority);
}

Add missing methods to interface

Add missing methods to interface


<?php

/* Find the authentication state. */
if (!array_key_exists('AuthState', $_REQUEST) || empty($_REQUEST['AuthState'])) {
	throw new SimpleSAML_Error_BadRequest('Missing mandatory parameter: AuthState');
}

$authState = $_REQUEST['AuthState'];
$state = SimpleSAML_Auth_State::loadState($authState, 'openid:init');
$sourceId = $state['openid:AuthId'];
$authSource = SimpleSAML_Auth_Source::getById($sourceId);
if ($authSource === NULL) {
	throw new SimpleSAML_Error_BadRequest('Invalid AuthId \'' . $sourceId . '\' - not found.');
}

try {
	if (!empty($_GET['openid_url'])) {
		$authSource->doAuth($state, (string)$_GET['openid_url']);
	}
} catch (Exception $e) {
	$error = $e->getMessage();
}

$config = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($config, 'openid:consumer.php', 'openid');
$t->data['error'] = $error;
$t->data['AuthState'] = $authState;
$t->show();

<?php

/* Find the authentication state. */
if (!array_key_exists('AuthState', $_REQUEST) || empty($_REQUEST['AuthState'])) {
	throw new SimpleSAML_Error_BadRequest('Missing mandatory parameter: AuthState');
}

$authState = $_REQUEST['AuthState'];
$state = SimpleSAML_Auth_State::loadState($authState, 'openid:init');
$sourceId = $state['openid:AuthId'];
$authSource = SimpleSAML_Auth_Source::getById($sourceId);
if ($authSource === NULL) {
	throw new SimpleSAML_Error_BadRequest('Invalid AuthId \'' . $sourceId . '\' - not found.');
}

$error = NULL;
try {
	if (!empty($_GET['openid_url'])) {
		$authSource->doAuth($state, (string)$_GET['openid_url']);
	}
} catch (Exception $e) {
	$error = $e->getMessage();
}

$config = SimpleSAML_Configuration::getInstance();
$t = new SimpleSAML_XHTML_Template($config, 'openid:consumer.php', 'openid');
$t->data['error'] = $error;
$t->data['AuthState'] = $authState;
$t->show();

openid: Fix notice about unititialized variable.


<?php
namespace Concrete\Core\Form\Service\Widget;
use Loader;
use View;
use Request;
class Typography {

    /**
     * Creates form fields and JavaScript includes to add a font picker widget.
     *
     *     $dh->output('background-color', '#f00');
     *
     * @param string $inputName
     * @param array $value
     * @param array $options
     */
    public function output($inputName, $value = array(), $options = array()) {
        $view = View::getInstance();
        $view->requireAsset('core/style-customizer');

        $options['inputName'] = $inputName;
        $options = array_merge($options, $value);
        $strOptions = json_encode($options);

        print '';
        print "";

    }

}

<?php
namespace Concrete\Core\Form\Service\Widget;
use View;
class Typography
{
    /**
     * Creates form fields and JavaScript includes to add a font picker widget.
     *
     *     $dh->output('background-color', '#f00');
     *
     * @param string $inputName
     * @param array  $value
     * @param array  $options
     */
    public function output($inputName, $value = array(), $options = array())
    {
        $view = View::getInstance();
        $view->requireAsset('core/style-customizer');

        $options['inputName'] = $inputName;
        $options = array_merge($options, $value);
        $strOptions = json_encode($options);

        print '';
        print "";

    }

}

Update PSR-2 and remove unused use

Update PSR-2 and remove unused use

Former-commit-id: e54069691862a3c7d4249b624a720b9a536875cc


<?php
    namespace DB;

    class Result
    {
        private $sql;
        private $data;

        public function __construct($sql, $data)
        {
            $this->sql = $sql;
            $this->data = $data;
        }

        public function syntax()
        {
            return $this->sql;
        }
    }

?>

<?php
    namespace DB;

    class Result
    {
        private $sql;
        private $data;

        private $pos = 0;

        public function __construct($sql, $data)
        {
            $this->sql = $sql;
            $this->data = $data;
        }

        public function syntax()
        {
            return $this->sql;
        }

        public function row()
        {
            return isset($this->data[$this->pos]) ? $this->data[$this->pos++] : false;
        }
    }

?>

Add method to get data per row

Add method to get data per row


<?php

/*
 * This file is part of the Cocorico package.
 *
 * (c) Cocolabs SAS <contact@cocolabs.io>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Cocorico\CoreBundle\DependencyInjection\Compiler;

use Cocorico\CoreBundle\Twig\TranslationExtension;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class TwigTranslationExtensionCompilerPass implements CompilerPassInterface
{
    /**
     * {@inheritDoc}
     */
    public function process(ContainerBuilder $container)
    {
        /**
         * Override Twig Translation extension
         */
        if ($container->hasDefinition('twig.extension.trans')) {
            $definition = $container->getDefinition('twig.extension.trans');
            $definition->setClass(TranslationExtension::class);
            $definition->addMethodCall(
                'setCheckTranslation',
                array($container->getParameter('cocorico.check_translation'))
            );
        }
    }
}

<?php

/*
 * This file is part of the Cocorico package.
 *
 * (c) Cocolabs SAS <contact@cocolabs.io>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Cocorico\CoreBundle\DependencyInjection\Compiler;

use Cocorico\CoreBundle\Twig\TranslationExtension;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class TwigTranslationExtensionCompilerPass implements CompilerPassInterface
{
    /**
     * {@inheritDoc}
     */
    public function process(ContainerBuilder $container)
    {
        /**
         * Override Twig Translation extension
         */
        if ($container->getParameter('cocorico.check_translation') === true) {
            if ($container->hasDefinition('twig.extension.trans')) {
                $definition = $container->getDefinition('twig.extension.trans');
                $definition->setClass(TranslationExtension::class);
                $definition->addMethodCall(
                    'setCheckTranslation',
                    array($container->getParameter('cocorico.check_translation'))
                );
            }
        }
    }
}

Add condition to replace Translation extension


<?php
class order_RemoveCartLineAction extends f_action_BaseAction
{
	/**
	 * @param Context $context
	 * @param Request $request
	 */
	public function _execute($context, $request)
	{
		$cartService = order_CartService::getInstance();
		$cart = $cartService->getDocumentInstanceFromSession();
		$cartLineIndex = $request->getParameter('cartLineIndex');

		if (!f_util_StringUtils::isEmpty($cartLineIndex) && !is_null($cart))
		{
			$cartService->removeLine($cart, $cartLineIndex);
			$cartService->refresh($cart);
		}

		$pageId = $request->getParameter('pageref', null);
		$url = null;
		if (is_numeric($pageId))
		{
			$url = LinkHelper::getDocumentUrl(DocumentHelper::getDocumentInstance($pageId, 'modules_website/page'));
		}
		$context->getController()->redirectToUrl(str_replace('&', '&', $url));

		return View::NONE;
	}

	/**
	 * @return boolean
	 */
	public function isSecure()
	{
		return false;
	}
}

<?php
class order_RemoveCartLineAction extends f_action_BaseAction
{
	/**
	 * @param Context $context
	 * @param Request $request
	 */
	public function _execute($context, $request)
	{
		$cartService = order_CartService::getInstance();
		$cart = $cartService->getDocumentInstanceFromSession();
		$cartLineIndex = $request->getParameter('cartLineIndex');

		if (!f_util_StringUtils::isEmpty($cartLineIndex) && !is_null($cart))
		{
			$cartService->removeLine($cart, $cartLineIndex);
			$cartService->refresh($cart);
		}

		$pageId = $request->getParameter('pageref', null);

		if (is_numeric($pageId))
		{
			$url = LinkHelper::getDocumentUrl(DocumentHelper::getDocumentInstance($pageId, 'modules_website/page'));
		}
		else
		{
			$url = $_SERVER['HTTP_REFERER'];
		}
		$context->getController()->redirectToUrl(str_replace('&', '&', $url));

		return View::NONE;
	}

	/**
	 * @return boolean
	 */
	public function isSecure()
	{
		return false;
	}
}

[NEW] Remove cart line can redirect to referer


<?php
$this->load->view("partial/header");
?>

<?php echo $title ?>

<?php echo $subtitle ?>

<?php
?>

<?php foreach($summary_data as $name=>$value) { ?>

<?php echo $this->lang->line('reports_'.$name). ': '.to_currency($value); ?>

<?php }?>

<?php
$this->load->view("partial/footer");
?>

Implement fix for Open Flash Chart not displaying in Firefox.

Tom

git-svn-id: ec090d62484f5211934fcf70a1de07e1dda17a57@56 c3eb156b-1dc0-44e1-88ae-e38439141b53


<?php

namespace Brendt\Stitcher\Template\Smarty;

use \Smarty;
use Brendt\Stitcher\Template\TemplateEngine;
use Symfony\Component\Finder\SplFileInfo;

/**
 * The Smarty template engine.
 */
class SmartyEngine extends Smarty implements TemplateEngine
{
    public function __construct($templateDir = './src', $cacheDir = './.cache') {
        parent::__construct();

        $this->addTemplateDir($templateDir);
        $this->setCompileDir($cacheDir);
        $this->addPluginsDir([__DIR__]);

        $this->caching = false;
    }

    public function renderTemplate(SplFileInfo $template) {
        return $this->fetch($template->getRealPath());
    }

    public function addTemplateVariables(array $variables) {
        foreach ($variables as $name => $variable) {
            $this->assign($name, $variable);
        }

        return $this;
    }

    public function clearTemplateVariables() {
        $this->clearAllAssign();

        return $this;
    }

    public function addTemplateVariable($name, $value) {
        $this->assign($name, $value);

        return $this;
    }

    public function hasTemplateVariable(string $name) : bool {
        return $this->getTemplateVars($name) != null;
    }

    public function clearTemplateVariable($variable) {
        $this->clearAssign($variable);

        return $this;
    }

    public function getTemplateExtensions(): array {
        return ['html', 'tpl'];
    }
}

<?php

namespace Brendt\Stitcher\Template\Smarty;

use \Smarty;
use Brendt\Stitcher\Template\TemplateEngine;
use Symfony\Component\Finder\SplFileInfo;

/**
 * The Smarty template engine.
 */
class SmartyEngine extends Smarty implements TemplateEngine
{
    public function __construct($templateDir = './src', $cacheDir = './.cache') {
        parent::__construct();

        $this->addTemplateDir($templateDir);
        $this->setCompileDir($cacheDir);
        $this->addPluginsDir([__DIR__]);

        $this->caching = false;
    }

    public function renderTemplate(SplFileInfo $template) {
        return $this->fetch($template->getRealPath());
    }

    public function addTemplateVariables(array $variables) {
        foreach ($variables as $name => $variable) {
            $this->assign($name, $variable);
        }

        return $this;
    }

    public function clearTemplateVariables() {
        $this->clearAllAssign();

        return $this;
    }

    public function addTemplateVariable($name, $value) {
        $this->assign($name, $value);

        return $this;
    }

    public function hasTemplateVariable(string $name) : bool {
        return $this->getTemplateVars($name) != null;
    }

    public function clearTemplateVariable($variable) {
        $this->clearAssign($variable);

        return $this;
    }

    public function getTemplateExtensions(): array {
        return ['tpl'];
    }
}

Remove extension conflict between Twig and Smarty


<?php
/**
 * @title          Interface Api Class
 *
 * @author         Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright      (c) 2012-2016, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Module / Connect / Inc / Class
 * @version        1.1
 */
namespace PH7;
defined('PH7') or exit('Restricted access');

interface IApi
{

    /**
     * Set an user authentication.
     *
     * @param integer $iId
     * @param object \PH7\UserCoreModel $oUserModel
     * @return void
     */
    public function setLogin($iId, UserCoreModel $oUserModel);

    /**
     * Set Avatar.
     *
     * @param string $sUrl URL of avatar.
     * @return void
     */
    public function setAvatar($sUrl);

    /**
     * Get Avatar.
     *
     * @param string $sUrl
     * @return string The Avatar
     */
     public function getAvatar($sUrl);

    /**
     * Add User.
     *
     * @param array $aData
     * @param object \PH7\UserCoreModel $oUserModel
     * @return void
     */
    public function add(array $aData, UserCoreModel $oUserModel);

}

<?php
/**
 * @title          Interface Api Class
 *
 * @author         Pierre-Henry Soria <ph7software@gmail.com>
 * @copyright      (c) 2012-2016, Pierre-Henry Soria. All Rights Reserved.
 * @license        GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
 * @package        PH7 / App / System / Module / Connect / Inc / Class
 * @version        1.1
 */
namespace PH7;
defined('PH7') or exit('Restricted access');

interface IApi
{

    /**
     * Set an user authentication.
     *
     * @param integer $iId
     * @param object \PH7\UserCoreModel $oUserModel
     * @return void
     */
    public function setLogin($iId, UserCoreModel $oUserModel);

    /**
     * Set Avatar.
     *
     * @param string $sUrl URL of avatar.
     * @return void
     */
    public function setAvatar($sUrl);

    /**
     * Get Avatar.
     *
     * @param string $sUrl
     * @return string The Avatar
     */
     public function getAvatar($sUrl);
}

Remove interface method "add" since Facebook class work differently so not nedded anymore


<?php

class CadastroController extends \HXPHP\System\Controller
{
	public function cadastrarAction()
	{
		$this->view->setFile('index');

		$this->request->setCustomFilters(array(
			'email' => FILTER_VALIDATE_EMAIL
		));

		$post = $this->request->post();

		if (!empty($post)) {
			$cadastrarUsuario = User::cadastrar($post);

			if ($cadastrarUsuario->status === false) {
				$this->load('Helpers\Alert', array(
					'danger',
					'Ops! Não foi possível efetuar seu cadastro. <br> Verifique os erros abaixo:',
					$cadastrarUsuario->errors
				));
			}
		}
	}
}

<?php

class CadastroController extends \HXPHP\System\Controller
{
    public function __construct($configs) {
        parent::__construct($configs);
        $this->load(
        'Services\Auth',
        $configs->auth->after_login,
        $configs->auth->after_logout,
         TRUE
                );
                $this->auth->redirectCheck(TRUE);
    }

    public function cadastrarAction()
	{
		$this->view->setFile('index');

		$this->request->setCustomFilters(array(
			'email' => FILTER_VALIDATE_EMAIL
		));

		$post = $this->request->post();

		if (!empty($post)) {
			$cadastrarUsuario = User::cadastrar($post);

			if ($cadastrarUsuario->status === false) {
				$this->load('Helpers\Alert', array(
					'danger',
					'Ops! Não foi possível efetuar seu cadastro. <br> Verifique os erros abaixo:',
					$cadastrarUsuario->errors
				));
			}
		}
	}
}

Add serviço Auth no construtor

Add serviço Auth no construtor


<?php
/**
 * Do not edit this file. Edit the config files found in the ../config/ dir instead.
 * This file is required in the root directory so WordPress can find it.
 * WP is hardcoded to look in its own directory or one directory up for wp-config.php.
 */

$host_config_dir  = dirname(__FILE__) . '/../config/';
$host_config_file = $host_config_dir . preg_replace("/[^a-z0-9]+/", "-", strtolower($_SERVER['HTTP_HOST'])) . ".php";
$defaults_file    = $host_config_dir . "defaults.php";

/** Include the host-specific config file if it exists. */
if (file_exists($host_config_file))
  require_once($host_config_file);

/** Include the default fallbacks file. */
if (file_exists($defaults_file))
  require_once($defaults_file);

/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
  define('ABSPATH', dirname(__FILE__) . '/');

/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');

/** Fix for connection errors on localhost. */
if( WP_ENV == 'development' ) {
  add_filter( 'http_api_transports', function() {
    return array( 'streams' );
  });
}

Add fix for connection errors on localhost. Probably could be fixed by a setting in cURL but this works for now


<?php

namespace Emonkak\Random\Tests\Engine;

use Emonkak\Random\Engine\RandomDevice;

/**
 * @requires extension mcrypt
 */
class RandomDeviceTest extends \PHPUnit_Framework_TestCase
{
    public function testMax()
    {
        return $this->assertSame(0x7fffffff, (new RandomDevice())->max());
    }

    public function testMin()
    {
        return $this->assertSame(0, (new RandomDevice())->min());
    }

    public function testNext()
    {
        $engine = new RandomDevice();

        for ($i = 0; $i < 1000; $i++) {
            $n = $engine->next();

            $this->assertGreaterThanOrEqual($engine->min(), $n);
            $this->assertLessThanOrEqual($engine->max(), $n);
        }
    }
}

<?php

namespace Emonkak\Random\Tests\Engine;

use Emonkak\Random\Engine\RandomDevice;

/**
 * @requires extension mcrypt
 */
class RandomDeviceTest extends \PHPUnit_Framework_TestCase
{
    public function testMax()
    {
        $engine = new RandomDevice();
        return $this->assertSame(0x7fffffff, $engine->max());
    }

    public function testMin()
    {
        $engine = new RandomDevice();
        return $this->assertSame(0, $engine->min());
    }

    public function testNext()
    {
        $engine = new RandomDevice();

        for ($i = 0; $i < 1000; $i++) {
            $n = $engine->next();

            $this->assertGreaterThanOrEqual($engine->min(), $n);
            $this->assertLessThanOrEqual($engine->max(), $n);
        }
    }
}

Fix test failure on php 5.3

Fix test failure on php 5.3


<?php

class Default_View_Helper_Link extends Zend_View_Helper_Abstract
{
	public function link(Default_Model_Movie $movie, $displayUrl = false)
	{
		$url =  $movie->getImdbUrl();
		$result = '' . $this->view->translate('IMDb') . '';

		if ($displayUrl)
		{
			$result .= ' ' . $url . '';
		}

		return $result;
	}
}

?>

FIX broken link on movie page

FIX broken link on movie page


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

namespace Darvin\ContentBundle\Twig\Extension;

use Darvin\ContentBundle\Widget\WidgetEmbedderInterface;

/**
 * Widget Twig extension
 */
class WidgetExtension extends \Twig_Extension
{
    /**
     * @var \Darvin\ContentBundle\Widget\WidgetEmbedderInterface
     */
    private $widgetEmbedder;

    /**
     * @param \Darvin\ContentBundle\Widget\WidgetEmbedderInterface $widgetEmbedder Widget embedder
     */
    public function __construct(WidgetEmbedderInterface $widgetEmbedder)
    {
        $this->widgetEmbedder = $widgetEmbedder;
    }

    /**
     * {@inheritdoc}
     */
    public function getFilters()
    {
        return [
            new \Twig_SimpleFilter('content_embed_widgets', [$this->widgetEmbedder, 'embed'], ['is_safe' => ['html']]),
        ];
    }

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

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

namespace Darvin\ContentBundle\Twig\Extension;

use Darvin\ContentBundle\Widget\WidgetEmbedderInterface;

/**
 * Widget Twig extension
 */
class WidgetExtension extends \Twig_Extension
{
    /**
     * @var \Darvin\ContentBundle\Widget\WidgetEmbedderInterface
     */
    private $widgetEmbedder;

    /**
     * @param \Darvin\ContentBundle\Widget\WidgetEmbedderInterface $widgetEmbedder Widget embedder
     */
    public function __construct(WidgetEmbedderInterface $widgetEmbedder)
    {
        $this->widgetEmbedder = $widgetEmbedder;
    }

    /**
     * {@inheritdoc}
     */
    public function getFilters()
    {
        return [
            new \Twig_SimpleFilter('content_embed_widgets', [$this->widgetEmbedder, 'embed'], ['is_safe' => ['html']]),
        ];
    }
}

Replace deprecated "getName()" method from Twig extensions.


<?php

require_once(__DIR__ . '/../../opensrs/openSRS_loader.php');

class openSRS_OpsTest extends PHPUnit_Framework_TestCase
{
    /**
     * Should convert specials chars, & encode in utf8
     *
     * @return void
     */
    public function testQuoteXMLChars()
    {
        $ops = new openSRS_ops;
        $data = 'This is my & < > \' " string';
        $result = $ops->_quoteXMLChars($data);

        /// chars should be converted
        $this->assertEquals($result, 'This is my & < > ' " string');

        // should be utf8
        $this->assertTrue(mb_check_encoding($result, 'UTF-8'));
    }

    /**
     * Should return true for associative, and false for plain
     *
     * @return void
     */
    public function testIsAssoc()
    {
        $ops = new openSRS_ops;
        $no = array(1, 2, 3, 4);
        $yes = array('this' => 'is', 'associative');

        $this->assertfalse($ops->_is_assoc($no));
        $this->assertTrue($ops->_is_assoc($yes));
    }
}

<?php

require_once(__DIR__ . '/../../opensrs/openSRS_loader.php');

class openSRS_OpsTest extends PHPUnit_Framework_TestCase
{
    /**
     * Should convert specials chars, & encode in utf8
     *
     * @return void
     */
    public function testQuoteXMLChars()
    {
        $ops = new openSRS_ops;
        $data = 'This is my & < > \' " string';
        $result = $ops->_quoteXMLChars($data);

        /// chars should be converted
        $this->assertEquals($result, 'This is my & < > ' " string');

        // should be utf8
        $this->assertTrue(mb_check_encoding($result, 'UTF-8'));
    }

    /**
     * Should return true for associative, and false for plain
     *
     * @return void
     */
    public function testIsAssoc()
    {
        $ops = new openSRS_ops;
        $no = array(1, 2, 3, 4);
        $yes = array('this' => 'is', 'associative');

        $this->assertFalse($ops->_is_assoc($no));
        $this->assertTrue($ops->_is_assoc($yes));
    }

    /**
     * Should convert php array to formmated xml
     *
     * @return void
     */
    public function testPhp2Xml()
    {
        $ops = new openSRS_ops;
        $data = array('convert' => 'this');
        $result = $ops->PHP2XML($data);

        $this->assertEquals($result, "  <data_block>\n   <dt_assoc>\n   <item key=\"convert\">this</item>\n   </dt_assoc>\n  </data_block>");
    }
}

Add test for php to xml convenience function


<?php
if( isset( $_GET[ 'live' ] ) ):
    $apiResponse = json_decode( file_get_contents( 'https://api.twitch.tv/kraken/streams?game=Hearthstone:%20Heroes%20of%20Warcraft' ) );
    $files = array();
    foreach( $apiResponse->streams as $stream ):
        $previewUrl = str_replace( '{width}', 1920, $stream->preview->template );
        $previewUrl = str_replace( '{height}', 1080, $previewUrl );
        $files[] = 'imgproxy.php?url=' . $previewUrl;
    endforeach;
else :
    $files = glob( "img/*.jpg" );
endif;

echo json_encode( $files );

<?php
if( isset( $_GET[ 'live' ] ) ):
    $apiResponse = json_decode( file_get_contents( 'https://api.twitch.tv/kraken/streams?game=Hearthstone:%20Heroes%20of%20Warcraft' ) );
    $files = array();
    foreach( $apiResponse->streams as $stream ):
        $previewUrl = str_replace( '{width}', 1920, $stream->preview->template );
        $previewUrl = str_replace( '{height}', 1080, $previewUrl );
        $files[] = 'imgproxy.php?url=' . $previewUrl;
    endforeach;
else :
    $files = glob( "img/*.jpg" );
    natsort( $files );
    $files = array_values( $files );
endif;

echo json_encode( $files );

Return test-files in natural order

Return test-files in natural order


<?php

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/

$factory->define(\App\Models\User::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->email,
        'password' => bcrypt(str_random(10)),
        'remember_token' => str_random(10),
    ];
});

<?php

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/

$getFaker = function(){
    $locales = ['en_US', 'uk_UA', 'ru_RU'];
    $randomKey = array_rand($locales, 1);
    return Faker\Factory::create($locales[$randomKey]);
};

$factory->define(\App\Models\User::class, function() use ($getFaker) {
    $faker = $getFaker();

    return [
        'name' => $faker->name,
        'email' => $faker->email,
        'password' => bcrypt(str_random(10)),
        'remember_token' => str_random(10),
    ];
});

Update factories to use uk/en/ru languages


has('serial') ? ' has-error' : '' }}">
    {{ trans('admin/hardware/form.serial') }}

        <input class="form-control" type="text" name="serial" id="serial" value="{{ old('serial', $item->serial) }}" />
        {!! $errors->first('serial', ' :message') !!}

has('serial') ? ' has-error' : '' }}">
    {{ trans('admin/hardware/form.serial') }}

        <input class="form-control" type="text" name="{{ $fieldname }}" id="{{ $fieldname }}" value="{{ old('serial', $item->serial) }}" />
        {!! $errors->first('serial', ' :message') !!}

Change the form input name for serials in the view


<?php

namespace Busuu\IosReceiptsApi;

use GuzzleHttp\Client;

class AppleClient
{
    /** @var  Client $client */
    private $client;
    /** @var  string */
    private $password;

    public function __construct($password)
    {
        $this->client = new Client();
        $this->password = $password;
    }

    /**
     * Fetch the receipt from apple
     *
     * @param $receiptData
     * @param $endpoint
     * @return array
     */
    public function fetchReceipt($receiptData, $endpoint)
    {
        try {
            $data = [
                'password' => $this->password,
                'receipt-data' => $receiptData
            ];

            $response = $this->client->post($endpoint, ['body' => json_encode($data)]);

            return json_decode($response->getBody(), true);
        } catch (\Exception $e) {
            throw new \InvalidArgumentException(
                sprintf('Error in the communication with Apple - %s', $e->getMessage())
            );
        }
    }
}

<?php

namespace Busuu\IosReceiptsApi;

use Exception;
use GuzzleHttp\Client;

class AppleClient
{
    /** @var  Client $client */
    private $client;
    /** @var  string */
    private $password;

    public function __construct($password)
    {
        $this->client = new Client();
        $this->password = $password;
    }

    /**
     * Fetch the receipt from apple
     *
     * @param $receiptData
     * @param $endpoint
     *
     * @return array
     * @throws Exception
     */
    public function fetchReceipt($receiptData, $endpoint)
    {
        $data = [
            'password' => $this->password,
            'receipt-data' => $receiptData
        ];

        $response = $this->client->post($endpoint, [
            'body' => json_encode($data),
            'timeout' => 10
        ]);

        $jsonResponse = json_decode($response->getBody(), true);

        if (null !== $jsonResponse) {
            return $jsonResponse;
        }

        throw new Exception(sprintf('Invalid Response from Apple Server: %s', $response));
    }
}

Add error checking on invalid json

Add error checking on invalid json


<?php

namespace ATPViz\Widget;

class DataTable extends \ATPViz\Widget\AbstractWidget
{
	public function __construct()
	{
		parent::__construct();

		$this->setTemplate('atp-viz/widget/dataTable.phtml');
	}

	public function getClasses($row)
	{
		$classes = array();
		if(isset($this->classFields))
		{
			foreach($this->classFields as $field)
			{
				$value = $row[$field];
				$method = "get{$field}Class";
				if(method_exists($this, $method)) $value = $this->$method($value);

				$classes[] = str_replace(" ", "-", "{$field}-{$value}");
			}
		}

		return implode(" ", $classes);
	}

	public function getSampleData()
	{
		return array(
			'columns' => array('First Column', 'Second Column', 'Third Column'),
			'data' => array(
				array(1, 2, 3),
				array(4, 5, 6),
				array(7, 8, 9)
			)
		);
	}
}

<?php

namespace ATPViz\Widget;

class DataTable extends \ATPViz\Widget\AbstractWidget
{
	public function __construct()
	{
		parent::__construct();

		$this->setTemplate('atp-viz/widget/dataTable.phtml');
	}

	public function getClasses($row)
	{
		$classes = array();
		if(isset($this->classFields))
		{
			foreach($this->classFields as $field)
			{
				$value = $row[$field];
				$method = "get{$field}Class";
				if(method_exists($this, $method)) $value = $this->$method($value);

				$class = str_replace(array("/", " "), "-", trim("{$field}-{$value}"));
				while(strpos($class, "--") !== false) $class = str_replace("--", "-", $class);
				$classes[] = $class;
			}
		}

		return implode(" ", $classes);
	}

	public function getSampleData()
	{
		return array(
			'columns' => array('First Column', 'Second Column', 'Third Column'),
			'data' => array(
				array(1, 2, 3),
				array(4, 5, 6),
				array(7, 8, 9)
			)
		);
	}
}

Clean up data table value-based row classes


<?php

namespace Yajra\Acl;

use Closure;

class CanAtLeastAuthorization
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @param  string $permissions
     * @return mixed
     */
    public function handle($request, Closure $next, $permissions)
    {
        $abilities = explode(',', $permissions);

        if (! auth()->check() || ! auth()->user()->canAtLeast($abilities)) {
            abort(403, 'You are not allowed to view this content!');
        }

        return $next($request);
    }
}

Add new line at EOF.

Add new line at EOF.


<?php

namespace App\Http\Controllers;

use App\Invoice;
use App\Book;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Services\Purchase;

class Purchases extends Controller
{

    /**
     * Purchase book and generate invoice.
     *
     * @param  Request  $request
     * @return Response
     */
    public function index(Request $request) {
        $invoice = null;
        $purchaseService = new Purchase();
        $purchaseQty = $request->input('qty');
        $book = Invoice::find($request->input('book_id'));
        $purchasePrice = $purchaseService->purchaseBook($book,$purchaseQty);

        if($purchasePrice !== null) {
            $invoice = new Invoice();
            $invoice->book_id = $book->id;
            $invoice->amount = $purchasePrice;
            $invoice->qty = $purchaseQty;
            $invoice->created_at = date('Y-m-d H:i:s');
            $invoice->updated_at = date('Y-m-d H:i:s');
            $invoice->save();
        }

        return $invoice;
    }
}

<?php

namespace App\Http\Controllers;

use App\Invoice;
use App\Book;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Services\Purchase;

class Purchases extends Controller
{

    /**
     * Purchase book and generate invoice.
     *
     * @param  Request  $request
     * @return Response
     */
    public function index(Request $request) {
        $invoice = null;
        $purchaseService = new Purchase();
        $purchaseQty = $request->input('qty');
        $book = Book::find($request->input('book_id'));
        $purchasePrice = $purchaseService->purchaseBook($book,$purchaseQty);

        if($purchasePrice !== null) {
            $invoice = new Invoice();
            $invoice->book_id = $book->id;
            $invoice->amount = $purchasePrice;
            $invoice->qty = $purchaseQty;
            $invoice->created_at = date('Y-m-d H:i:s');
            $invoice->updated_at = date('Y-m-d H:i:s');
            $invoice->save();
        }

        return $invoice;
    }
}

Add purchase functionality in back-end.

Add purchase functionality in back-end.


<?php

namespace Oro\Bundle\DataGridBundle\Extension\Export;

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

class Configuration implements ConfigurationInterface
{
    const XLSX_MAX_EXPORT_RECORDS = 10;

    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $builder = new TreeBuilder();

        $builder->root('export')
            ->treatTrueLike(
                [
                    'csv' => [
                        'label' => 'oro.grid.export.csv'
                    ],
                    'xlsx' => [
                        'label' => 'oro.grid.export.xlsx',
                        'show_max_export_records_dialog' => true,
                        'max_export_records' => self::XLSX_MAX_EXPORT_RECORDS
                    ]
                ]
            )
            ->treatFalseLike([])
            ->treatNullLike([])
            ->useAttributeAsKey('name')
            ->prototype('array')
                ->children()
                    ->scalarNode('label')
                        ->cannotBeEmpty()
                    ->end()
                    ->booleanNode('show_max_export_records_dialog')
                    ->end()
                    ->integerNode('max_export_records')
                    ->end()
                ->end()
            ->end();

        return $builder;
    }
}

<?php

namespace Oro\Bundle\DataGridBundle\Extension\Export;

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

class Configuration implements ConfigurationInterface
{
    const XLSX_MAX_EXPORT_RECORDS = 10000;

    /**
     * {@inheritDoc}
     */
    public function getConfigTreeBuilder()
    {
        $builder = new TreeBuilder();

        $builder->root('export')
            ->treatTrueLike(
                [
                    'csv' => [
                        'label' => 'oro.grid.export.csv'
                    ],
                    'xlsx' => [
                        'label' => 'oro.grid.export.xlsx',
                        'show_max_export_records_dialog' => true,
                        'max_export_records' => self::XLSX_MAX_EXPORT_RECORDS
                    ]
                ]
            )
            ->treatFalseLike([])
            ->treatNullLike([])
            ->useAttributeAsKey('name')
            ->prototype('array')
                ->children()
                    ->scalarNode('label')
                        ->cannotBeEmpty()
                    ->end()
                    ->booleanNode('show_max_export_records_dialog')
                    ->end()
                    ->integerNode('max_export_records')
                    ->end()
                ->end()
            ->end();

        return $builder;
    }
}

BAP-11307: Create notice popup for xlsx grid export
- fix maximum number


<?php

namespace PhpSpec\Wrapper\Subject\Expectation;

use Exception;
use PhpSpec\Exception\Example\ErrorException;
use PhpSpec\Util\Instantiator;
use PhpSpec\Wrapper\Subject\WrappedObject;

class ConstructorDecorator extends Decorator implements ExpectationInterface
{
    public function __construct(ExpectationInterface $expectation)
    {
        $this->setExpectation($expectation);
    }

    public function match($alias, $subject, array $arguments = array(), WrappedObject $wrappedObject = null)
    {
        try {
            $wrapped = $subject->getWrappedObject();
        } catch (ErrorException $e) {
            throw $e;
        } catch (Exception $e) {
            if ($wrappedObject->getClassName()) {
                $instantiator = new Instantiator();
                $wrapped = $instantiator->instantiate($wrappedObject->getClassName());
            }
        }

        return $this->getExpectation()->match($alias, $wrapped, $arguments);
    }
}

<?php

namespace PhpSpec\Wrapper\Subject\Expectation;

use Exception;
use PhpSpec\Exception\Example\ErrorException;
use PhpSpec\Util\Instantiator;
use PhpSpec\Wrapper\Subject\WrappedObject;

class ConstructorDecorator extends Decorator implements ExpectationInterface
{
    public function __construct(ExpectationInterface $expectation)
    {
        $this->setExpectation($expectation);
    }

    public function match($alias, $subject, array $arguments = array(), WrappedObject $wrappedObject = null)
    {
        try {
            $wrapped = $subject->getWrappedObject();
        } catch (ErrorException $e) {
            throw $e;
        } catch (Exception $e) {
            if (null !== $wrappedObject && $wrappedObject->getClassName()) {
                $instantiator = new Instantiator();
                $wrapped = $instantiator->instantiate($wrappedObject->getClassName());
            }
        }

        return $this->getExpectation()->match($alias, $wrapped, $arguments);
    }
}

Make sure wrappedObject is not null before making a method call on it


<?php

namespace React\Socket;

use Evenement\EventEmitter;
use React\EventLoop\LoopInterface;
use React\Stream\WritableStreamInterface;
use React\Stream\Buffer;
use React\Stream\Stream;
use React\Stream\Util;

class Connection extends Stream implements ConnectionInterface
{
    public function handleData($stream)
    {
        $data = stream_socket_recvfrom($stream, $this->bufferSize);
        if ('' === $data || false === $data) {
            $this->end();
        } else {
            $this->emit('data', array($data, $this));
        }
    }

    public function handleClose()
    {
        if (is_resource($this->stream)) {
            stream_socket_shutdown($this->stream, STREAM_SHUT_RDWR);
            fclose($this->stream);
        }
    }

    public function getRemoteAddress()
    {
        return $this->parseAddress(stream_socket_get_name($this->stream, true));
    }

    private function parseAddress($address)
    {
        return trim(substr($address, 0, strrpos($address, ':')), '[]');
    }
}

<?php

namespace React\Socket;

use Evenement\EventEmitter;
use React\EventLoop\LoopInterface;
use React\Stream\WritableStreamInterface;
use React\Stream\Buffer;
use React\Stream\Stream;
use React\Stream\Util;

class Connection extends Stream implements ConnectionInterface
{
    public function handleData($stream)
    {
        $data = fread($stream, $this->bufferSize);
        if ('' === $data || false === $data) {
            $this->end();
        } else {
            $this->emit('data', array($data, $this));
        }
    }

    public function handleClose()
    {
        if (is_resource($this->stream)) {
            stream_socket_shutdown($this->stream, STREAM_SHUT_RDWR);
            fclose($this->stream);
        }
    }

    public function getRemoteAddress()
    {
        return $this->parseAddress(stream_socket_get_name($this->stream, true));
    }

    private function parseAddress($address)
    {
        return trim(substr($address, 0, strrpos($address, ':')), '[]');
    }
}

Use fread() instead of socket_recv_from()


<?php
namespace Stirling\Database;

/**
 * Interface for Entities.
 *
 * An Entity is a class created from database data.
 *
 * @package Stirling\Database
 */
interface IEntity
{
    public function getKey();
}

<?php
namespace Stirling\Database;

/**
 * Interface for Entities.
 *
 * An Entity is a class created from database data.
 *
 * @package Stirling\Database
 */
interface IEntity
{
    public function getKey();

    public function getProperties();
}

Add getProperty function to return all properties


<?php

namespace BenAllfree\Trackable\Models;

use Illuminate\Database\Eloquent\Model;

class Action extends Model
{
  protected $fillable = ['contact_id', 'event', 'ip_address', 'user_agent', 'referer', 'url', 'exited_at', 'request_method'];
  protected $dates = ['created_at', 'updated_at', 'exited_at'];

  static function goal($contact_id, $event, $data=[])
  {
    $a = self::create([
      'contact_id'=>$contact_id,
      'event'=>$event,
      'ip_address'=>\Request::server('REMOTE_ADDR'),
      'user_agent'=>\Request::server('HTTP_USER_AGENT'),
      'referer'=>\Request::server('HTTP_REFERER'),
      'url'=>\Request::url(),
      'request_method'=>\Request::server('REQUEST_METHOD'),
    ]);
    foreach($data as $k=>$v)
    {
      \ActionMeta::create([
        'action_id'=>$a->id,
        'key'=>$k,
        'value'=>$v,
      ]);
    }
    return $a;
  }
}

<?php

namespace BenAllfree\Trackable\Models;

use Illuminate\Database\Eloquent\Model;

class Action extends Model
{
  protected $fillable = ['contact_id', 'event', 'ip_address', 'user_agent', 'referer', 'url', 'exited_at', 'request_method'];
  protected $dates = ['created_at', 'updated_at', 'exited_at'];

  static function goal($contact_id, $event, $data=[])
  {
    $a = self::create([
      'contact_id'=>$contact_id,
      'event'=>$event,
      'ip_address'=>\Request::server('REMOTE_ADDR'),
      'user_agent'=>\Request::server('HTTP_USER_AGENT'),
      'referer'=>\Request::server('HTTP_REFERER'),
      'url'=>\Request::url(),
      'request_method'=>\Request::server('REQUEST_METHOD'),
    ]);
    foreach($data as $k=>$v)
    {
      \ActionMeta::create([
        'action_id'=>$a->id,
        'key'=>$k,
        'value'=>json_encode($v),
      ]);
    }
    return $a;
  }
}

Save action meat as JSON

Save action meat as JSON


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

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

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

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

      <?php endif; ?>

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

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

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

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

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

            <?php include roots_template_path(); ?>

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

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

This reverts commit 9831a5f3e60457ac87b1b4a83000b0aee5a027b8.


<?php

use Roots\Sage\Setup;
use Roots\Sage\Wrapper;

?>

<!doctype html>
<html <?php language_attributes(); ?>>
  <?php get_template_part('templates/head'); ?>
  <body <?php body_class(); ?>>

    <?php
      do_action('get_header');
      get_template_part('templates/header');
    ?>

          <?php include Wrapper\template_path(); ?>

        <?php if (Setup\display_sidebar()) : ?>

            <?php include Wrapper\sidebar_path(); ?>

        <?php endif; ?>

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

<?php

use Roots\Sage\Setup;
use Roots\Sage\Wrapper;

?>

<!doctype html>
<html <?php language_attributes(); ?>>
  <?php get_template_part('templates/head'); ?>
  <body <?php body_class('has-drawer'); ?>>

    <?php
      do_action('get_header');
      get_template_part('templates/header');
    ?>

          <?php include Wrapper\template_path(); ?>

        <?php if (Setup\display_sidebar()) : ?>

            <?php include Wrapper\sidebar_path(); ?>

        <?php endif; ?>

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

Update body class for drawer.

Update body class for drawer.


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

  <?php
    do_action('get_header');
    // Use Bootstrap's navbar if enabled in config.php
    if (current_theme_supports('bootstrap-top-navbar')) {
      get_template_part('templates/header-top-navbar');
    } else {
      get_template_part('templates/header');
    }
  ?>

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

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

      <?php endif; ?>

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

Change IE conditional statement so alert appears on IE7

Bootstrap 3 no longer supports IE7. The roots outdated browser warning should now appear on anything earlier than IE8.