<?php

namespace MCordingley\LaravelSapient\Middleware;

use Closure;
use Illuminate\Http\Request;
use MCordingley\LaravelSapient\Contracts\KeyResolver;
use ParagonIE\ConstantTime\Base64UrlSafe;
use ParagonIE\Sapient\CryptographyKeys\SigningPublicKey;
use Symfony\Component\HttpFoundation\Response;

final class VerifyRequest
{
    /** @var KeyResolver */
    private $resolver;

    /**
     * @param KeyResolver $resolver
     */
    public function __construct(KeyResolver $resolver)
    {
        $this->resolver = $resolver;
    }

    /**
     * @param Request $request
     * @param Closure $next
     * @return Response
     */
    public function handle(Request $request, Closure $next): Response
    {
        $signature = $request->headers->get('Body-Signature-Ed25519');
        $key = new SigningPublicKey(Base64UrlSafe::decode($this->resolver->resolveKey()));

        if (!sodium_crypto_sign_verify_detached($this->decode($signature), $request->getContent(), $key->getString(true))) {
            abort(403, 'Invalid Sapient signature detected.');
        }

        return $next($request);
    }
}

<?php

namespace MCordingley\LaravelSapient\Middleware;

use Closure;
use Illuminate\Http\Request;
use MCordingley\LaravelSapient\Contracts\KeyResolver;
use ParagonIE\ConstantTime\Base64UrlSafe;
use ParagonIE\Sapient\CryptographyKeys\SigningPublicKey;
use Symfony\Component\HttpFoundation\Response;

final class VerifyRequest
{
    /** @var KeyResolver */
    private $resolver;

    /**
     * @param KeyResolver $resolver
     */
    public function __construct(KeyResolver $resolver)
    {
        $this->resolver = $resolver;
    }

    /**
     * @param Request $request
     * @param Closure $next
     * @return Response
     */
    public function handle(Request $request, Closure $next): Response
    {
        $key = new SigningPublicKey(Base64UrlSafe::decode($this->resolver->resolveKey()));

        foreach ($request->headers->get('Body-Signature-Ed25519', null, false) as $signature) {
            if (sodium_crypto_sign_verify_detached(Base64UrlSafe::decode($signature), $request->getContent(), $key->getString(true))) {
                return $next($request);
            }
        }

        abort(403, 'Invalid Sapient signature detected.');
    }
}

Handle array of values for the MAC.

Handle array of values for the MAC.


<?php

namespace Kibo\Phast\Services\Bundler;

use Kibo\Phast\Cache\File\Cache;
use Kibo\Phast\Filters\CSS;
use Kibo\Phast\Filters\Service\CachingServiceFilter;
use Kibo\Phast\Retrievers\CachingRetriever;
use Kibo\Phast\Retrievers\LocalRetriever;
use Kibo\Phast\Retrievers\RemoteRetrieverFactory;
use Kibo\Phast\Retrievers\UniversalRetriever;
use Kibo\Phast\Security\ServiceSignatureFactory;
use Kibo\Phast\Services\ServiceFactoryTrait;

class Factory {
    use ServiceFactoryTrait;

    public function make(array $config) {
        $cssServiceFactory = new \Kibo\Phast\Services\Css\Factory();
        $jsServiceFactory = new \Kibo\Phast\Services\Scripts\Factory();

        $cssFilter = $this->makeCachingServiceFilter(
            $config,
            $cssServiceFactory->makeFilter($config),
            'bundler-css'
        );

        $jsFilter = $this->makeCachingServiceFilter(
            $config,
            $jsServiceFactory->makeFilter(),
            'bundler-js'
        );

        return new Service(
            (new ServiceSignatureFactory())->make($config),
            $cssServiceFactory->makeRetriever($config),
            $cssFilter,
            $jsServiceFactory->makeRetriever($config),
            $jsFilter
        );
    }

}

<?php

namespace Kibo\Phast\Services\Bundler;

use \Kibo\Phast\Services\Css;
use \Kibo\Phast\Services\Scripts;
use Kibo\Phast\Security\ServiceSignatureFactory;
use Kibo\Phast\Services\ServiceFactoryTrait;

class Factory {
    use ServiceFactoryTrait;

    public function make(array $config) {
        $cssServiceFactory = new Css\Factory();
        $jsServiceFactory = new Scripts\Factory();

        $cssFilter = $this->makeCachingServiceFilter(
            $config,
            $cssServiceFactory->makeFilter($config),
            'bundler-css'
        );

        $jsFilter = $this->makeCachingServiceFilter(
            $config,
            $jsServiceFactory->makeFilter(),
            'bundler-js'
        );

        return new Service(
            (new ServiceSignatureFactory())->make($config),
            $cssServiceFactory->makeRetriever($config),
            $cssFilter,
            $jsServiceFactory->makeRetriever($config),
            $jsFilter
        );
    }

}

Use namespaces in bundler factory

Use namespaces in bundler factory


<?php

return array(
    // Native language name
    'language' => array('it_IT' => 'Italiano'),
    'englishlang' => array('it_IT' => 'Italian'),
    // Possible locale for language
    'locale' => array('it_IT' => 'it_IT,it_IT.utf8,it_IT.utf-8,it_IT.UTF-8,it_IT@euro,italian,Italian_Italy.1252'),
    // Encoding of the language
    'encoding' => array('it_IT' => 'UTF-8'),
    // Direction of the language
    'direction' => array('it_IT' => 'ltr'),
    // Possible aliases for language
    'alias' => array(
        'it' => 'it_IT',
        'italiano' => 'it_IT',
        'ita' => 'it_IT',
        'italian' => 'it_IT',
        'it_IT.ISO8859-1' => 'it_IT',
        'it_IT.ISO8859-15' => 'it_IT',
    ),
);

<?php

return array(
    // Native language name
    'language' => array('it_IT' => 'Italiano'),
    'englishlang' => array('it_IT' => 'Italian'),
    // Possible locale for language
    'locale' => array('it_IT' => 'it,it_IT,it_IT.utf8,it_IT.utf-8,it_IT.UTF-8,it_IT@euro,italian,Italian_Italy.1252'),
    // Encoding of the language
    'encoding' => array('it_IT' => 'UTF-8'),
    // Direction of the language
    'direction' => array('it_IT' => 'ltr'),
    // Possible aliases for language
    'alias' => array(
        'it' => 'it_IT',
        'italiano' => 'it_IT',
        'ita' => 'it_IT',
        'italian' => 'it_IT',
        'it_IT.ISO8859-1' => 'it_IT',
        'it_IT.ISO8859-15' => 'it_IT',
    ),
);

Add "it" as locale alias for it_IT

Add "it" as locale alias for it_IT


<?php

// the str_replace was necessary when using a namespace because it was using
// a backslash in the path instead of forward slash
spl_autoload_register(function ($class) {
    $include_path = '/Users/cary/src/git/xsearch/php/phpsearch/';
    include $include_path . str_replace("\\", "/", strtolower($class)) . '.php';
});

?>

<?php

// the str_replace was necessary when using a namespace because it was using
// a backslash in the path instead of forward slash
spl_autoload_register(function ($class) {
	$HOME = getenv('HOME');
    $include_path = "$HOME/src/git/xsearch/php/phpsearch/";
    include $include_path . str_replace("\\", "/", strtolower($class)) . '.php';
});

?>

Use HOME env var in php

Use HOME env var in php


<?php
/**
 * @package Gabrieljmj\Lousql
 * @author  Gabriel Jacinto aka. GabrielJMJ <gamjj74@hotmail.com>
 * @license MIT License
 */

namespace Gabrieljmj\Lousql\Builder;

/**
 * Interface for SQL builders
 */
interface BuilderInterface
{
    /**
     * Creates an SQL table
     *
     * @param string $table
     */
    public function createTable($table);

    /**
     * Alters an SQL table
     *
     * @param string $table
     */
    public function alterTable($table);
}

<?php
/**
 * @package Gabrieljmj\Lousql
 * @author  Gabriel Jacinto aka. GabrielJMJ <gamjj74@hotmail.com>
 * @license MIT License
 */

namespace Gabrieljmj\Lousql\Builder;

/**
 * Interface for SQL builders
 */
interface BuilderInterface
{
    /**
     * Creates an SQL table
     *
     * @param string $table
     */
    public function createTable($table);

    /**
     * Alters an SQL table
     *
     * @param string $table
     */
    public function alterTable($table);

    /**
     * Returns all created queries
     *
     * @return array
     */
    public function getQueries();
}

Add method getQueries to interface for builders


<?php

// default settings

define('XMLSERVICELIB', 'ZENDSVR6');   //library with IBM XMLTOOLKIT objects
define('DFTLIB', 'QGPL');              //library for creation of temporary objects
define('ZSTOOLKITLIB', 'ZENDSVR6');    //library with service program
define('ZSTOOLKITPGM', 'ZSXMLSRV');    //service program name
define('DBPROTOCOL', 'ibm_db2');
define('XMLINTERNALKEY', '/tmp/Toolkit'); // default IPC (InternalKey)

<?php

// default settings

define('XMLSERVICELIB', 'ZENDPHP7');   //library with IBM XMLTOOLKIT objects
define('DFTLIB', 'QGPL');              //library for creation of temporary objects
define('ZSTOOLKITLIB', 'ZENDPHP7');    //library with service program
define('ZSTOOLKITPGM', 'ZSXMLSRV');    //service program name
define('DBPROTOCOL', 'ibm_db2');
define('XMLINTERNALKEY', '/tmp/Toolkit'); // default IPC (InternalKey)

Use ZS9 library in default settings

Use ZS9 library in default settings


<?php
namespace Auth;

class Authenticator
{
    public function login($username, $password)
    {
        return false;
    }

    public function is_logged_in($data)
    {
        return false;
    }

    public function get_user($data)
    {
        return null;
    }

    public function get_group_by_name($name)
    {
        return null;
    }

    public function get_user_by_name($name)
    {
        return null;
    }

    public function get_groups_by_filter($filter, $select=false, $top=false, $skip=false, $orderby=false)
    {
        return false;
    }

    public function get_users_by_filter($filter, $select=false, $top=false, $skip=false, $orderby=false)
    {
        return false;
    }

    public function get_active_user_count()
    {
        $users = $this->get_users_by_filter(false);
        if($users === false)
        {
            return 0;
        }
        return count($users);
    }

    public function get_pending_user_count()
    {
        return 0;
    }

    public function get_group_count()
    {
        $groups = $this->get_groups_by_filter(false);
        if($groups === false)
        {
            return 0;
        }
        return count($groups);
    }
}
?>

<?php
namespace Auth;

class Authenticator
{
    const SUCCESS         = 0;
    const ALREADY_PRESENT = 1;
    const LOGIN_FAILED    = 2;

    public $current = false;
    public $pending = false;
    public $supplement = false;

    public function __construct($params)
    {
        $this->current = $params['current'];
        $this->pending = $params['pending'];
        $this->supplement = $params['supplement'];
    }

    public function login($username, $password)
    {
        return false;
    }

    public function is_logged_in($data)
    {
        return false;
    }

    public function get_user($data)
    {
        return null;
    }

    public function get_group_by_name($name)
    {
        return null;
    }

    public function get_user_by_name($name)
    {
        return null;
    }

    public function get_groups_by_filter($filter, $select=false, $top=false, $skip=false, $orderby=false)
    {
        return false;
    }

    public function get_users_by_filter($filter, $select=false, $top=false, $skip=false, $orderby=false)
    {
        return false;
    }

    public function get_active_user_count()
    {
        $users = $this->get_users_by_filter(false);
        if($users === false)
        {
            return 0;
        }
        return count($users);
    }

    public function get_pending_user_count()
    {
        return 0;
    }

    public function get_group_count()
    {
        $groups = $this->get_groups_by_filter(false);
        if($groups === false)
        {
            return 0;
        }
        return count($groups);
    }

    public function get_supplement_link()
    {
        return false;
    }
}
?>

Add support for suplementary authentication


<?php

namespace fennecweb\ajax\listing;

use \PDO as PDO;

/**
 * Web Service.
 * Returns information of all users projects
 */
class Projects extends \fennecweb\WebService
{
    const ERROR_NOT_LOGGED_IN = "Error. Not logged in.";

    private $db;
    /**
    * @param $querydata[]
    * @returns Array $result
    * <code>
    * array(array('project_id','import_date','OTUs','sample size'));
    * </code>
    */
    public function execute($querydata)
    {
        $this->db = $this->openDbConnection($querydata);
        $result = array();
        if (!isset($_SESSION['user'])) {
            $result = array("error" => Projects::ERROR_NOT_LOGGED_IN);
        }
        return $result;
    }
}

<?php

namespace fennecweb\ajax\listing;

use \PDO as PDO;

/**
 * Web Service.
 * Returns information of all users projects
 */
class Projects extends \fennecweb\WebService
{
    const ERROR_NOT_LOGGED_IN = "Error. Not logged in.";

    private $db;
    /**
    * @param $querydata[]
    * @returns Array $result
    * <code>
    * array(array('project_id','import_date','OTUs','sample size'));
    * </code>
    */
    public function execute($querydata)
    {
        $db = $this->openDbConnection($querydata);
        $result = array();
        if (!isset($_SESSION['user'])) {
            $result = array("error" => Projects::ERROR_NOT_LOGGED_IN);
        }
        return $result;
    }
}

Add correct db variable to execute function


<?php

class Denkmal_Response_Api_MessageTest extends CMTest_TestCase {

	protected function setUp() {
		CM_Config::get()->Denkmal_Site->url = 'http://denkmal.test';
	}

	public function tearDown() {
		CMTest_TH::clearEnv();
	}

	public function testMatch() {
		$request = new CM_Request_Post('/api/message', array('host' => 'denkmal.test'));
		$response = CM_Response_Abstract::factory($request);
		$this->assertInstanceOf('Denkmal_Response_Api_Message', $response);
	}

	public function testProcess() {
		$venue = Denkmal_Model_Venue::create(array('name' => 'Example', 'queued' => true, 'enabled' => false));

		$body = 'venue=' . urlencode($venue->getId()) . '&text=' . urlencode('hallo test');
		$request = new CM_Request_Post('/api/message', array('host' => 'denkmal.test'), $body);
		$response = new Denkmal_Response_Api_Message($request);
		$response->process();
	}
}

<?php

class Denkmal_Response_Api_MessageTest extends CMTest_TestCase {

	protected function setUp() {
		CM_Config::get()->Denkmal_Site->url = 'http://denkmal.test';
	}

	public function tearDown() {
		CMTest_TH::clearEnv();
	}

	public function testMatch() {
		$request = new CM_Request_Post('/api/message', array('host' => 'denkmal.test'));
		$response = CM_Response_Abstract::factory($request);
		$this->assertInstanceOf('Denkmal_Response_Api_Message', $response);
	}

	public function testProcess() {
		$venue = Denkmal_Model_Venue::create(array('name' => 'Example', 'queued' => true, 'enabled' => false));

		$body = 'venue=' . urlencode($venue->getId()) . '&text=' . urlencode('hallo test');
		$request = new CM_Request_Post('/api/message', array('host' => 'denkmal.test'), $body);
		$response = new Denkmal_Response_Api_Message($request);
		$response->process();

		$messageList = new Denkmal_Paging_Message_All();
		$this->assertCount(1, $messageList);
		/** @var Denkmal_Model_Message $message */
		$message = $messageList->getItem(0);
		$this->assertEquals($venue, $message->getVenue());
		$this->assertSame('hallo test', $message->getText());
		$this->assertSameTime(time(), $message->getCreated());
	}
}

Check for message model in api response

Check for message model in api response


<?php

namespace Fire\Business\Model;

class ExternalAccount {
    protected $properties = array();

    public function __construct(\stdClass $rawData) {

        $this->properties = array(
            'id' => $rawData->{'id'},
            'alias' => $rawData->{'alias'},
            'nsc' => @$rawData->{'nsc'},
            'accountNumber' => @$rawData->{'accountNumber'},
            'bic' => @$rawData->{'bic'},
            'iban' => @$rawData->{'iban'}
        );

    }

    public function get($key) {
        return $this->properties[$key];
    }

    /**
     * Provide a friendly representation
     *
     * @return string friendly representation
     */
    public function __toString() {
        $context = array();
        foreach ($this->properties as $key => $value) {
            if ($value instanceof \DateTime) {
                $context[] = "$key=".$value->format('Y-m-d\TH:i:s');
            } else {
                $context[] = "$key=$value";
            }
        }
        return '[ Fire.Business.Model.ExternalAccount: ' . implode(' ', $context) . ' ]';
    }

}

<?php

namespace Fire\Business\Model;

class ExternalAccount {
    protected $properties = array();

    public function __construct(\stdClass $rawData) {

        $this->properties = array(
            'id' => property_exists($rawData, 'id') ? $rawData->{'id'} : null,
            'alias' => $rawData->{'alias'},
            'nsc' => @$rawData->{'nsc'},
            'accountNumber' => @$rawData->{'accountNumber'},
            'bic' => @$rawData->{'bic'},
            'iban' => @$rawData->{'iban'}
        );

    }

    public function get($key) {
        return $this->properties[$key];
    }

    /**
     * Provide a friendly representation
     *
     * @return string friendly representation
     */
    public function __toString() {
        $context = array();
        foreach ($this->properties as $key => $value) {
            if ($value instanceof \DateTime) {
                $context[] = "$key=".$value->format('Y-m-d\TH:i:s');
            } else {
                $context[] = "$key=$value";
            }
        }
        return '[ Fire.Business.Model.ExternalAccount: ' . implode(' ', $context) . ' ]';
    }

}

Check 'id' exists before accessing the value


<?php

namespace Saxulum\Tests\DoctrineMongoDbOdm\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

/**
 * @ODM\Document
 */
class Page
{
    /**
     * @var string
     * @ODM\Id
     */
    protected $id;

    /**
     * @var string
     * @ODM\String
     */
    protected $title;

    /**
     * @var string
     * @ODM\String
     */
    protected $body;

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

    /**
     * @param $title
     * @return $this
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

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

    /**
     * @param $body
     * @return $this
     */
    public function setBody($body)
    {
        $this->body = $body;

        return $this;
    }

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

<?php

namespace Saxulum\Tests\DoctrineMongoDbOdm\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;

/**
 * @ODM\Document
 */
class Page
{
    /**
     * @var string
     * @ODM\Id
     */
    protected $id;

    /**
     * @var string
     * @ODM\Field(type="string")
     */
    protected $title;

    /**
     * @var string
     * @ODM\Field(type="string")
     */
    protected $body;

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

    /**
     * @param $title
     * @return $this
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

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

    /**
     * @param $body
     * @return $this
     */
    public function setBody($body)
    {
        $this->body = $body;

        return $this;
    }

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

Remove String annotations, use Field instead


<?php

class Scrivener {

	private static $_instance;

	private function __construct() {
		add_filter( 'preview_post_link', array( $this, 'filter_preview_post_link' ) );
	}

	public function filter_preview_post_link() {

	}

	/**
	 * Initialize class and return an instance of it
	 *
	 * @since 0.1.0
	 * @return Scrivener
	 */
	public function init() {
		if ( ! isset( self::$_instance ) ) {

			self::$_instance = new Scrivener;
		}

		return self::$_instance;
	}

}

<?php

class Scrivener {

	private static $_instance;

	/**
	 * Setup singleton Scrivener instance
	 *
	 * @since 0.1.0
	 * @uses add_filter
	 * @return void
	 */
	private function __construct() {
		add_filter( 'preview_post_link', array( $this, 'filter_preview_post_link' ) );
	}

	/**
	 * Filter preview post link
	 *
	 * @param string $link
	 * @since 0.1.0
	 * @uses admin_url
	 * @return string
	 */
	public function filter_preview_post_link( $link ) {
		global $post;
		return admin_url( 'admin-post.php?weiverp=1&p=' . $post->ID );
	}

	/**
	 * Initialize class and return an instance of it
	 *
	 * @since 0.1.0
	 * @return Scrivener
	 */
	public function init() {
		if ( ! isset( self::$_instance ) ) {
			self::$_instance = new Scrivener;
		}

		return self::$_instance;
	}

}

Scrivener::init();

Add meat to preview link filter

Add meat to preview link filter


<?php

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

namespace Symfony\Component\Security\Csrf;

/**
 * A CSRF token.
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class CsrfToken
{
    private $id;
    private $value;

    public function __construct(string $id, ?string $value)
    {
        $this->id = $id;
        $this->value = $value ?? '';
    }

    /**
     * Returns the ID of the CSRF token.
     *
     * @return string The token ID
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Returns the value of the CSRF token.
     *
     * @return string The token value
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * Returns the value of the CSRF token.
     *
     * @return string The token value
     */
    public function __toString()
    {
        return $this->value;
    }
}

<?php

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

namespace Symfony\Component\Security\Csrf;

/**
 * A CSRF token.
 *
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class CsrfToken
{
    private $id;
    private $value;

    public function __construct(string $id, ?string $value)
    {
        $this->id = $id;
        $this->value = $value ?? '';
    }

    /**
     * Returns the ID of the CSRF token.
     *
     * @return string The token ID
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Returns the value of the CSRF token.
     *
     * @return string The token value
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * Returns the value of the CSRF token.
     */
    public function __toString(): string
    {
        return $this->value;
    }
}

Add return type to __toString()

Add return type to __toString()


<?php

$Reference = [
  ['Titre' => 'Telephone1', 'Description' => 'BlaBla1', 'Image' => '', 'Texte' => 'Texte1'];

  ['Titre' => 'Telephone2', 'Description' => 'BlaBla2', 'Image' => '', 'Texte' => 'Texte2'];

  ['Titre' => 'Telephone3', 'Description' => 'BlaBla3', 'Image' => '', 'Texte' => 'Texte3'];

];

 ?>

<?php

$Reference = [
  ['Titre' => 'Telephone1', 'Description' => 'BlaBla1', 'Image' => '', 'Texte' => 'Texte1'],

  ['Titre' => 'Telephone2', 'Description' => 'BlaBla2', 'Image' => '', 'Texte' => 'Texte2'],

  ['Titre' => 'Telephone3', 'Description' => 'BlaBla3', 'Image' => '', 'Texte' => 'Texte3'],

];

 ?>

Add Change to End Of Array

Add Change to End Of Array


<?php

namespace AlgoliaSearch;

/**
 * Class Json.
 */
class Json
{
    public static function encode($value, $options = 0)
    {
        $json = json_encode($value, $options);

        self::checkError();

        return $json;
    }

    public static function decode($json, $assoc = false, $depth = 512)
    {
        $value = json_decode($json, $assoc, $depth);
        if (null === $value)
            print_r($json);

        self::checkError();

        return $value;
    }

    private static function checkError()
    {
        $error = json_last_error();

        if (!$error) {
            return;
        }

        $errorMsg = 'JSON error';
        switch ($error) {
            case JSON_ERROR_DEPTH:
                $errorMsg = 'JSON parsing error: maximum stack depth exceeded';
                break;
            case JSON_ERROR_CTRL_CHAR:
                $errorMsg = 'JSON parsing error: unexpected control character found';
                break;
            case JSON_ERROR_SYNTAX:
                $errorMsg = 'JSON parsing error: syntax error, malformed JSON';
                break;
            case JSON_ERROR_STATE_MISMATCH:
                $errorMsg = 'JSON parsing error: underflow or the modes mismatch';
                break;
            // PHP 5.3 less than 1.2.2 (Ubuntu 10.04 LTS)
            case defined('JSON_ERROR_UTF8') ? JSON_ERROR_UTF8 : -1:
                $errorMsg = 'JSON parsing error: malformed UTF-8 characters, possibly incorrectly encoded';
                break;
        }

        throw new AlgoliaException($errorMsg, $error);
    }
}

<?php

namespace AlgoliaSearch;

/**
 * Class Json.
 */
class Json
{
    public static function encode($value, $options = 0)
    {
        $json = json_encode($value, $options);

        self::checkError();

        return $json;
    }

    public static function decode($json, $assoc = false, $depth = 512)
    {
        $value = json_decode($json, $assoc, $depth);

        self::checkError();

        return $value;
    }

    private static function checkError()
    {
        $error = json_last_error();

        if (!$error) {
            return;
        }

        $errorMsg = 'JSON error';
        switch ($error) {
            case JSON_ERROR_DEPTH:
                $errorMsg = 'JSON parsing error: maximum stack depth exceeded';
                break;
            case JSON_ERROR_CTRL_CHAR:
                $errorMsg = 'JSON parsing error: unexpected control character found';
                break;
            case JSON_ERROR_SYNTAX:
                $errorMsg = 'JSON parsing error: syntax error, malformed JSON';
                break;
            case JSON_ERROR_STATE_MISMATCH:
                $errorMsg = 'JSON parsing error: underflow or the modes mismatch';
                break;
            // PHP 5.3 less than 1.2.2 (Ubuntu 10.04 LTS)
            case defined('JSON_ERROR_UTF8') ? JSON_ERROR_UTF8 : -1:
                $errorMsg = 'JSON parsing error: malformed UTF-8 characters, possibly incorrectly encoded';
                break;
        }

        throw new AlgoliaException($errorMsg, $error);
    }
}

Remove debugging code added in bec782c

Remove debugging code added in bec782c


<?php
/**
 * Documentation page actions
 */
class docPageActions extends dmFrontModuleActions
{
  public function executeUpdateFromGit(dmWebRequest $request)
  {
    //$this->forward404Unless($request->isMethod('post'));

    // create a git repo
    require_once(sfConfig::get('sf_root_dir').'/lib/vendor/php-git-repo/lib/phpGitRepo.php');
    $repo = new phpGitRepo(sfConfig::get('sf_root_dir').'/data/diem-docs');

    // run the synchronizer
    $synchronizer = new gitDocumentationSynchronizer($repo);
    $synchronizer->execute();

    return $this->renderText('done');
  }

}

<?php
/**
 * Documentation page actions
 */
class docPageActions extends dmFrontModuleActions
{
  // handle GitHub post-receive hook
  public function executeUpdateFromGit(dmWebRequest $request)
  {
    $this->forward404Unless($request->isMethod('post'));

    $repoDir = sfConfig::get('sf_root_dir').'/data/diem-docs';

    // include phpGitRepo
    require_once(sfConfig::get('sf_root_dir').'/lib/vendor/php-git-repo/lib/phpGitRepo.php');

    // create a git repo instance
    $repo = new phpGitRepo($repoDir);

    // run the synchronizer passing it the repo instance
    $synchronizer = new gitDocumentationSynchronizer($repo);
    $synchronizer->execute();

    return $this->renderText('done');
  }

}

Add comments to the synchronization action


<?php

namespace MetaSyntactical\Http\Transport;

use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

interface TransportInterface
{
    /**
     * Send request and return response
     *
     * @param  RequestInterface  $request
     * @return ResponseInterface
     */
    public function send(RequestInterface $request);
}

<?php

namespace MetaSyntactical\Http\Transport;

use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

interface TransportInterface
{
    /**
     * Send request and return response
     *
     * @param  RequestInterface  $request
     * @return ResponseInterface
     */
    public function send(RequestInterface $request);

    /**
     * Create new request
     *
     * @return RequestInterface
     */
    public function newRequest();
}

Extend interface to require a method to create new requests


<?php

namespace App\Transformers\Outbound;

trait HasSuggestFields
{

    protected function getSuggestFields()
    {
        return array_replace_recursive(parent::getSearchFields(), [

            'suggest_autocomplete_boosted' => [
                'filter' => function ($item) {
                    return $item->isBoosted() && isset($item->title);
                },
            ],

            'suggest_autocomplete_all' => [
                'filter' => function ($item) {
                    return isset($item->title);
                },
            ],

        ]);
    }

}

<?php

namespace App\Transformers\Outbound;

trait HasSuggestFields
{

    protected function getSuggestFields()
    {
        return array_replace_recursive(parent::getSuggestFields(), [

            'suggest_autocomplete_boosted' => [
                'filter' => function ($item) {
                    return $item->isBoosted() && isset($item->title);
                },
            ],

            'suggest_autocomplete_all' => [
                'filter' => function ($item) {
                    return isset($item->title);
                },
            ],

        ]);
    }

}

Fix function reference in `getSuggestFields`


<?php
namespace DreamFactory\Core\SqlDb\Models;

/**
 * SqliteDbConfig
 *
 */
class SqliteDbConfig extends BaseSqlDbConfig
{
    protected $appends = ['database'];

    protected $rules = ['database' => 'required'];

    protected function getConnectionFields()
    {
        return ['database'];
    }

    public static function getDriverName()
    {
        return 'sqlite';
    }

    public static function getDefaultPort()
    {
        return null;
    }

    public static function getDefaultConnectionInfo()
    {
        $defaults = [
            [
                'name'        => 'database',
                'label'       => 'Database',
                'type'        => 'string',
                'description' => 'The name or path of the database to connect to. This can be a lookup key.'
            ],
        ];

        return $defaults;
    }
}

<?php
namespace DreamFactory\Core\SqlDb\Models;

use DreamFactory\Core\Exceptions\BadRequestException;

/**
 * SqliteDbConfig
 *
 */
class SqliteDbConfig extends BaseSqlDbConfig
{
    protected $appends = ['database'];

    public function validate($data, $throwException = true)
    {
        $connection = $this->getAttribute('connection');
        if (empty(array_get($connection, 'database'))) {
            throw new BadRequestException("Database connection information must contain at least database name.");
        }

        return parent::validate($data, $throwException);
    }

    protected function getConnectionFields()
    {
        return ['database'];
    }

    public static function getDriverName()
    {
        return 'sqlite';
    }

    public static function getDefaultPort()
    {
        return null;
    }

    public static function getDefaultConnectionInfo()
    {
        $defaults = [
            [
                'name'        => 'database',
                'label'       => 'Database',
                'type'        => 'string',
                'description' => 'The name or path of the database to connect to. This can be a lookup key.'
            ],
        ];

        return $defaults;
    }
}

Correct validation requirements for sqlite


<?php namespace Philipbrown\Math;

class Math {

  public function add($a, $b, $scale = 0)
  {
    return bcadd($a, $b, $scale);
  }

}

<?php namespace Philipbrown\Math;

class Math {

  /**
   * Add
   *
   * @param string $a
   * @param string $a
   * @param integer $scale
   * @return string
   */
  public function add($a, $b, $scale = 0)
  {
    return bcadd($a, $b, $scale);
  }

}

Add docblock to add method

Add docblock to add method


<?php

declare(strict_types=1);

namespace Rinvex\Fort\Traits;

use Rinvex\Fort\Notifications\PhoneVerificationNotification;

trait CanVerifyPhone
{
    /**
     * Get the phone for verification.
     *
     * @return string
     */
    public function getPhoneForVerification()
    {
        return $this->phone;
    }

    /**
     * Get the country for verification.
     *
     * @return string
     */
    public function getCountryForVerification()
    {
        $country = country($this->country_code);

        return $country ? $country->getCallingCode() : null;
    }

    /**
     * Determine if phone is verified or not.
     *
     * @return bool
     */
    public function isPhoneVerified()
    {
        return (bool) $this->phone_verified;
    }

    /**
     * Send the phone verification notification.
     *
     * @param string $method
     * @param bool   $force
     *
     * @return void
     */
    public function sendPhoneVerificationNotification($method, $force)
    {
        $this->notify(new PhoneVerificationNotification($method, $force));
    }
}

<?php

declare(strict_types=1);

namespace Rinvex\Fort\Traits;

use Rinvex\Fort\Notifications\PhoneVerificationNotification;

trait CanVerifyPhone
{
    /**
     * Get the phone for verification.
     *
     * @return string
     */
    public function getPhoneForVerification()
    {
        return $this->phone;
    }

    /**
     * Get the country for verification.
     *
     * @return string
     */
    public function getCountryForVerification()
    {
        return $this->country_code ? country($this->country_code)->getCallingCode() : null;
    }

    /**
     * Determine if phone is verified or not.
     *
     * @return bool
     */
    public function isPhoneVerified()
    {
        return (bool) $this->phone_verified;
    }

    /**
     * Send the phone verification notification.
     *
     * @param string $method
     * @param bool   $force
     *
     * @return void
     */
    public function sendPhoneVerificationNotification($method, $force)
    {
        $this->notify(new PhoneVerificationNotification($method, $force));
    }
}

Fix phone verification country getter issue


<?php

$date          =& $_REQUEST["date"];
$user          =& $_REQUEST["user"];
$priority      =& $_REQUEST["priority"];
$text          =& $_REQUEST["text"];

require_once 'icat.php';
$db = init_db();

$_SESSION['entry_username'] = $user;

$result = mysqli_query($db,
    "insert into entries (contest_time, user, priority, text) values " .
    sprintf("((SELECT MAX(contest_time) AS last_submission FROM submissions), '%s', %d, '%s')",
    mysqli_escape_string($db, $user), $priority, mysqli_escape_string($db, $text))
);

if ($result) {
    print("okay");
} else {
    print("error: " . mysqli_error($db));
}

?>

<?php

$date          =& $_REQUEST["date"];
$user          =& $_REQUEST["user"];
$priority      =& $_REQUEST["priority"];
$text          =& $_REQUEST["text"];
if (isset($_REQUEST["submission"])) {
    $sid       =  intval($_REQUEST["submission"]);
} else {
    $sid       =  null;
}

require_once 'icat.php';
$db = init_db();

$_SESSION['entry_username'] = $user;

$stmt = mysqli_prepare($db, 'INSERT INTO entries (contest_time, user, priority, text, submission_id) VALUES ((SELECT MAX(contest_time) AS last_submission FROM submissions), ?, ?, ?, ?)');

mysqli_stmt_bind_param($stmt, 'sisi', $user, $priority, $text, $sid);

mysqli_stmt_execute($stmt);

$error = mysqli_stmt_error($stmt);
if ($error === '') {
    print("okay");
} else {
    print("error: " . $error);
}

mysqli_stmt_close($stmt);

Insert into 'entries' using prepared statements, with submission ID


<?php
/**
 * This file has been made by pH7 (Pierre-Henry SORIA).
 */

namespace PFBC\Element;

use PFBC\Validation\Token as ValidationToken;
use PH7\Framework\Mvc\Model\DbConfig;
use PH7\Framework\Security\CSRF\Token as SecurityToken;

class Token extends Hidden
{

    private $sName;

    public function __construct($sName)
    {
        if (!$this->_isEnabled())
            return; // If it's disabled, we stop the execution of the class

        $this->sName = $sName;
        parent::__construct('security_token', (new SecurityToken)->generate($this->sName));
    }

    public function render()
    {
        if (!$this->_isEnabled())
            return; // If it's disabled, we stop the execution of the class

        $this->validation[] = new ValidationToken($this->sName);
        parent::render();
    }

    /**
     * Check if the CSRF security token for forms is enabled.
     *
     * @return boolean Returns TRUE if the security token is enabled, FALSE otherwise.
     */
    private function _isEnabled()
    {
        // Check if the CSRF security token for forms is enabled
        return DbConfig::getSetting('securityToken');
    }

}

<?php
/**
 * This file has been made by pH7 (Pierre-Henry SORIA).
 */

namespace PFBC\Element;

use PFBC\Validation\Token as ValidationToken;
use PH7\Framework\Mvc\Model\DbConfig;
use PH7\Framework\Security\CSRF\Token as SecurityToken;

class Token extends Hidden
{

    private $sName;

    public function __construct($sName)
    {
        if (!$this->isEnabled())
            return; // If it's disabled, we stop the execution of the class

        $this->sName = $sName;
        parent::__construct('security_token', (new SecurityToken)->generate($this->sName));
    }

    public function render()
    {
        if (!$this->isEnabled())
            return; // If it's disabled, we stop the execution of the class

        $this->validation[] = new ValidationToken($this->sName);
        parent::render();
    }

    /**
     * Check if the CSRF security token for forms is enabled.
     *
     * @return boolean Returns TRUE if the security token is enabled, FALSE otherwise.
     */
    private function isEnabled()
    {
        // Check if the CSRF security token for forms is enabled
        return DbConfig::getSetting('securityToken');
    }

}

Remove underscore prefixes from private functions


<?php

# See application/core/MY_Model for this parent model
class Team_stats_model extends Crud_model
{

  public function __construct()
  {
    parent::__construct();
    $this->table = 'team_stats';

  }

  public function all()
  {
    $res = $this->db->get($this->table)->result();

    /* we strip off useless zeros such as 60.00 to 60 or 79.70 to 79.9 */
    $this->formatFields($res);

    return $res;
  }

  public function getStatsByTeamId($team_id)
  {
    $this->db->where('team_id', $team_id);
    $res = $this->db->get($this->table)->result();

    $this->formatFields($res);

    return $res;
  }

  public function getDefaultTeamStats()
  {
    $this->load->model('Players_model');
    $default_team_id = $this->Players_model->getDefaultSquad()[0]->team_id; # Get a single player from a squad then get his ID
    $res = $this->getStatsByTeamId($default_team_id);
    $this->formatFields($res);

    return $res;
  }

  public function formatFields($res)
  {
    foreach($res as &$val) {
      $val->stat_value = floatval($val->stat_value);
    }
  }

}

<?php

# See application/core/MY_Model for this parent model
class Team_stats_model extends Crud_model
{

  public function __construct()
  {
    parent::__construct();
    $this->table = 'team_stats';

  }

  public function all()
  {
    $res = $this->db->get($this->table)->result();

    /* we strip off useless zeros such as 60.00 to 60 or 79.70 to 79.9 */
    $this->formatFields($res);

    return $res;
  }

  public function getStatsByTeamId($team_id)
  {
    $this->db->where('team_id', $team_id);
    $res = $this->db->get($this->table)->result();

    $this->formatFields($res);

    return $res;
  }

  public function getDefaultTeamStats()
  {
    $this->load->model('Players_model');
    $default_team_id = $this->getTeamIdByName(DEFAULT_SQUAD); # Find in constants
    $res = $this->getStatsByTeamId($default_team_id);
    $this->formatFields($res);

    return $res;
  }

  public function formatFields($res)
  {
    foreach($res as &$val) {
      $val->stat_value = floatval($val->stat_value);
    }
  }

}

Refactor getting the default team id

Refactor getting the default team id


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Alert;

class AlertsController extends Controller
{
  /**
   *
   */
  public function index()
  {
    $alerts = Alert::all();
    return view('alerts.index')->with('alerts', $alerts);
  }

  /**
   *
   */
  public function show($id) {

    $alert = Alert::find($id);
    return $alert;
  }
}

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Alert;

class AlertsController extends Controller
{
  /**
   *
   */
  public function index()
  {
    $alerts = Alert::all();
    return view('alerts.index')->with('alerts', $alerts);
  }

  /**
   *
   */
  public function show($id)
  {
    $alert = Alert::find($id);
    return view('alerts.show')->with('alert', $alert);
  }
}

Gather alert info and dsiplay on route

Gather alert info and dsiplay on route


Rename to new repository name

Rename to new repository name


<?php
/**
 * Email Interface
 *
 * @package    Email
 * @copyright  2013 Common Api. All rights reserved.
 * @license    http://www.opensource.org/licenses/mit-license.html MIT License
 */
namespace CommonApi\Email;

/**
 * Email Interface
 *
 * @package    Email
 * @license    http://www.opensource.org/licenses/mit-license.html MIT License
 * @copyright  2013 Common Api. All rights reserved.
 * @since      0.1
 */
interface EmailInterface
{
    /**
     * Send Email
     *
     * @return  mixed
     * @since   0.1
     */
    public function send();
}

<?php
/**
 * Email Interface
 *
 * @package    Email
 * @copyright  2013 Common Api. All rights reserved.
 * @license    http://www.opensource.org/licenses/mit-license.html MIT License
 */
namespace CommonApi\Email;

/**
 * Email Interface
 *
 * @package    Email
 * @license    http://www.opensource.org/licenses/mit-license.html MIT License
 * @copyright  2013 Common Api. All rights reserved.
 * @since      0.1
 */
interface EmailInterface
{
    /**
     * Return parameter value or default
     *
     * @param   string      $key
     * @param   null|string $default
     *
     * @return  mixed
     * @since   0.1
     */
    public function get($key, $default = null);

    /**
     * Set parameter value
     *
     * @param   string     $key
     * @param   null|mixed $value
     *
     * @return  mixed
     * @since   0.1
     */
    public function set($key, $value = null);

    /**
     * Send Email
     *
     * @return  $this
     * @since   0.1
     */
    public function send();
}

Add back get and set methods

Add back get and set methods


Add Pimple namespace to cache autoload

Add Pimple namespace to cache autoload


<?php

namespace Kunstmaan\MediaBundle\AdminList\ItemAction;

use Kunstmaan\AdminListBundle\AdminList\ItemAction\ItemActionInterface;

class MediaSelectItemAction implements ItemActionInterface
{
    /**
     * @param mixed $item
     *
     * @return array
     */
    public function getUrlFor($item)
    {
        return null;
    }

    /**
     * @param mixed $item
     *
     * @return string
     */
    public function getLabelFor($item)
    {
        return 'Select';
    }

    /**
     * @param mixed $item
     *
     * @return string
     */
    public function getIconFor($item)
    {
        return null;
    }

    /**
     * @return string
     */
    public function getTemplate()
    {
        return '@KunstmaanMedia/AdminList/ItemAction:select.html.twig';
    }
}

<?php

namespace Kunstmaan\MediaBundle\AdminList\ItemAction;

use Kunstmaan\AdminListBundle\AdminList\ItemAction\ItemActionInterface;

class MediaSelectItemAction implements ItemActionInterface
{
    /**
     * @param mixed $item
     *
     * @return array
     */
    public function getUrlFor($item)
    {
        return null;
    }

    /**
     * @param mixed $item
     *
     * @return string
     */
    public function getLabelFor($item)
    {
        return 'Select';
    }

    /**
     * @param mixed $item
     *
     * @return string
     */
    public function getIconFor($item)
    {
        return null;
    }

    /**
     * @return string
     */
    public function getTemplate()
    {
        return '@KunstmaanMedia/AdminList/ItemAction/select.html.twig';
    }
}

Fix typo in template path

[MediaBundle] Fix typo in template path


<?php

namespace Ddeboer\Imap;

class Server
{
    protected $hostname;
    protected $port;
    protected $connection;
    protected $mailboxes;

    public function __construct($hostname, $port = '993')
    {
        $this->server = '{' . $hostname . ':' . $port . '/imap}';
    }

    public function authenticate($username, $password)
    {
        $resource = @\imap_open($this->server, $username, $password, null, 1, array('DISABLE_AUTHENTICATOR' => 'GSSAPI'));

        // These are necessary to get rid of PHP throwing IMAP errors
        imap_errors();
        imap_alerts();

        return new Connection($resource, $this->server);
    }
}

<?php

namespace Ddeboer\Imap;

class Server
{
    protected $hostname;
    protected $port;
    protected $connection;
    protected $mailboxes;

    public function __construct($hostname, $port = '993')
    {
        $this->server = '{' . $hostname . ':' . $port . '/imap}';
    }

    public function authenticate($username, $password)
    {
        $resource = @\imap_open($this->server, $username, $password, null, 1, array('DISABLE_AUTHENTICATOR' => 'GSSAPI'));
        $check = imap_check($resource);
        $mailbox = $check->Mailbox;
        $this->connection = substr($mailbox, 0, strpos($mailbox, '}')+1);

        // These are necessary to get rid of PHP throwing IMAP errors
        imap_errors();
        imap_alerts();

        return new Connection($resource, $this->connection);
    }
}

Use connection string returned by PHP, to match mailbox name properly


<?php
/**
 * mailchimp-lib Magento Component
 *
 * @category Ebizmarts
 * @package mailchimp-lib
 * @author Ebizmarts Team <info@ebizmarts.com>
 * @copyright Ebizmarts (http://ebizmarts.com)
 * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 * @date: 5/2/16 5:23 PM
 * @file: Templates.php
 */
class Mailchimp_Templates extends Mailchimp_Abstract
{
    /**
     * @var Mailchimp_TemplatesDefaultContent
     */
    public $defaultContent;
}

<?php
/**
 * mailchimp-lib Magento Component
 *
 * @category Ebizmarts
 * @package mailchimp-lib
 * @author Ebizmarts Team <info@ebizmarts.com>
 * @copyright Ebizmarts (http://ebizmarts.com)
 * @license     http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 * @date: 5/2/16 5:23 PM
 * @file: Templates.php
 */
class Mailchimp_Templates extends Mailchimp_Abstract
{
    /**
     * @var Mailchimp_TemplatesDefaultContent
     */
    public $defaultContent;

    /**
     * @param int $id                   The store id.
     * @param string[] $fields          A comma-separated list of fields to return. Reference parameters of sub-objects with dot notation.
     * @param string[] $excludeFields   A comma-separated list of fields to exclude. Reference parameters of sub-objects with dot notation.
     * @param int $count                The number of records to return.
     * @param int $offset               The number of records from a collection to skip. Iterating over large collections with this parameter can be slow.
     * @return mixed
     * @throws \Mailchimp_Error
     * @throws \Mailchimp_HttpError
     */
    public function get($id=null,$fields=null,$excludeFields=null,$count=null,$offset=null)
    {
        $_params=array();
        if($fields) $_params['fields'] = $fields;
        if($excludeFields) $_params['exclude_fields'] = $excludeFields;
        if($count) $_params['count'] = $count;
        if($offset) $_params['offset'] = $offset;
        if($id) {
            return $this->master->call('templates/'.$id, $_params, \Mailchimp::GET);
        }
        else {
            return $this->master->call('templates', $_params, \Mailchimp::GET);
        }
    }
}

Implement retrieving list of templates

Implement retrieving list of templates


<?php

namespace Cube\DoctrineEntityFactory;
use Cube\DoctrineEntityFactory\Exception\InvalidArgumentException;

/**
 * Creates an entity directly - without passing any constructor arguments.
 *
 * @author Gabriel Somoza <gabriel.somoza@cu.be>
 */
final class SimpleEntityFactory implements EntityFactoryInterface
{
    /**
     * Gets an instance of the specified entity
     *
     * @param string $entityClassName
     *
     * @return object
     */
    public function get($entityClassName)
    {
        if (!is_string($entityClassName) || !class_exists($entityClassName)) {
            throw new InvalidArgumentException('Expected $entityClassName to be a valid class name.');
        }

        return new $entityClassName();
    }
}

Fix formatting for PSR-2 compliance

Fix formatting for PSR-2 compliance


<?php
/**
 * Uninstallation script for the plugin.
 *
 * @package   Google\Site_Kit
 * @copyright 2020 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

// Prevent execution from directly accessing the file.
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

// Load plugin main file to bootstrap infrastructure and add hooks.
require_once dirname( __FILE ) . '/google-site-kit.php';

// Fire action to trigger uninstallation logic.
do_action( 'googlesitekit_uninstallation' );

<?php
/**
 * Uninstallation script for the plugin.
 *
 * @package   Google\Site_Kit
 * @copyright 2020 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

// Prevent execution from directly accessing the file.
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

// Load plugin main file to bootstrap infrastructure and add hooks.
require_once dirname( __FILE__ ) . '/google-site-kit.php';

// Fire action to trigger uninstallation logic.
do_action( 'googlesitekit_uninstallation' );

Fix typo in file constant.

Fix typo in file constant.


<?php namespace Cerbero\Auth;

use Cerbero\Workflow\WorkflowServiceProvider;
use Illuminate\Support\ServiceProvider;

/**
 * Package service provider.
 *
 * @author	Andrea Marco Sartori
 */
class AuthServiceProvider extends ServiceProvider {

	/**
	 * Boot up the package.
	 *
	 * @return void
	 */
	public function boot()
	{
		$this->loadTranslationsFrom(__DIR__.'/../resources/lang', 'auth');

		$this->publishes([
			__DIR__.'/../config/_auth.php' => config_path('_auth.php'),
			__DIR__.'/../database/migrations/' => database_path('migrations'),
		]);

		include __DIR__.'/Http/routes.php';
	}

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		(new WorkflowServiceProvider($this->app))->register();

		$userRepo = 'Cerbero\Auth\Repositories\EloquentUserRepository';

		$this->app->bind('Cerbero\Auth\Repositories\UserRepositoryInterface', $userRepo);
	}

}

<?php namespace Cerbero\Auth;

use Cerbero\Workflow\WorkflowServiceProvider;
use Illuminate\Support\ServiceProvider;

/**
 * Package service provider.
 *
 * @author	Andrea Marco Sartori
 */
class AuthServiceProvider extends ServiceProvider {

	/**
	 * Boot up the package.
	 *
	 * @return void
	 */
	public function boot()
	{
		$this->loadTranslationsFrom(__DIR__.'/../resources/lang', 'auth');

		$this->publishes([
			__DIR__.'/../config/_auth.php' => config_path('_auth.php'),
			__DIR__.'/../database/migrations/' => base_path('database/migrations'),
		]);

		include __DIR__.'/Http/routes.php';
	}

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		(new WorkflowServiceProvider($this->app))->register();

		$userRepo = 'Cerbero\Auth\Repositories\EloquentUserRepository';

		$this->app->bind('Cerbero\Auth\Repositories\UserRepositoryInterface', $userRepo);
	}

}

Fix the path for the migrations

Fix the path for the migrations


<?php
namespace AppVentus\MangopayBundle\Helper;

use AppVentus\MangopayBundle\AppVentusMangopayEvents;
use AppVentus\MangopayBundle\Entity\UserInterface;
use AppVentus\MangopayBundle\Event\UserEvent;
use Doctrine\ORM\EntityManager;
use MangoPay\CardRegistration;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

/**
 *
 * ref: appventus_mangopay.card_registration_helper
 *
 **/
class CardRegistrationHelper
{
    private $mangopayHelper;
    private $entityManager;
    private $dispatcher;

    public function __construct(MangopayHelper $mangopayHelper, EntityManager $entityManager, EventDispatcherInterface $dispatcher)
    {
        $this->mangopayHelper = $mangopayHelper;
        $this->entityManager = $entityManager;
        $this->dispatcher = $dispatcher;
    }

    public function createCardRegistrationForUser(UserInterface $user)
    {

        $cardRegistration = new CardRegistration();
        $cardRegistration->userId = $user->getMangoUserId();
        $cardRegistration->Tag = 'user id : '.$user->getId();

        $cardRegistration = $this->mangopayHelper->CardRegistrations->Create($cardRegistration);

        return $cardRegistration;
    }
}

<?php
namespace AppVentus\MangopayBundle\Helper;

use AppVentus\MangopayBundle\AppVentusMangopayEvents;
use AppVentus\MangopayBundle\Entity\UserInterface;
use AppVentus\MangopayBundle\Event\UserEvent;
use Doctrine\ORM\EntityManager;
use MangoPay\CardRegistration;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;

/**
 *
 * ref: appventus_mangopay.card_registration_helper
 *
 **/
class CardRegistrationHelper
{
    private $mangopayHelper;
    private $entityManager;
    private $dispatcher;

    public function __construct(MangopayHelper $mangopayHelper, EntityManager $entityManager, EventDispatcherInterface $dispatcher)
    {
        $this->mangopayHelper = $mangopayHelper;
        $this->entityManager = $entityManager;
        $this->dispatcher = $dispatcher;
    }

    public function createCardRegistrationForUser(UserInterface $user)
    {

        $cardRegistration = new CardRegistration();
        $cardRegistration->userId = $user->getMangoUserId();
        $cardRegistration->Tag = 'user id : '.$user->getId();
        $cardRegistration->Currency = 'EUR';

        $cardRegistration = $this->mangopayHelper->CardRegistrations->Create($cardRegistration);

        return $cardRegistration;
    }
}

Add currency to card registration

Add currency to card registration


<?php namespace PhilipBrown\WorldPay;

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

class WorldPayServiceProvider extends ServiceProvider {

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

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

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

      $wp->setConfig(Config::get('worldpay'));
    });
    $this->app->booting(function()
    {
      $loader = AliasLoader::getInstance();
      $loader->alias('WorldPay', 'PhilipBrown\WorldPay\Facades\WorldPay');
    });
  }

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

}

<?php namespace PhilipBrown\WorldPay;

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

class WorldPayServiceProvider extends ServiceProvider {

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

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

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

      $wp->setConfig(Config::get('worldpay'));

      return $wp;
    });

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

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

}

Return WorldPay instance from Service Provider


<?php

/*
 * Copyright 2013 Johannes M. Schmitt <schmittjoh@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace JMS\Serializer\Tests\Fixtures;

use Doctrine\ORM\Proxy\Proxy;

class SimpleObjectProxy extends SimpleObject implements Proxy
{
    public $__isInitialized__ = false;

    private $baz = 'baz';

    public function __load()
    {
        if (!$this->__isInitialized__) {
            $this->camelCase = 'proxy-boo';
            $this->__isInitialized__ = true;
        }
    }

    public function __isInitialized()
    {
        return $this->__isInitialized__;
    }
}

<?php

/*
 * Copyright 2013 Johannes M. Schmitt <schmittjoh@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace JMS\Serializer\Tests\Fixtures;

use Doctrine\Common\Persistence\Proxy;

class SimpleObjectProxy extends SimpleObject implements Proxy
{
    public $__isInitialized__ = false;

    private $baz = 'baz';

    public function __load()
    {
        if (!$this->__isInitialized__) {
            $this->camelCase = 'proxy-boo';
            $this->__isInitialized__ = true;
        }
    }

    public function __isInitialized()
    {
        return $this->__isInitialized__;
    }
}

Change Proxy class used to Doctrine\Common\Persistence\Proxy


<?php namespace Coreplex\Meta;

use Illuminate\Support\ServiceProvider;

class MetaServiceProvider extends ServiceProvider {

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        // Set the files to publish
        $this->publishes([
            __DIR__.'/../config/meta.php' => config_path('meta.php'),
            __DIR__.'/../config/drivers.php' => config_path('drivers.php'),
            __DIR__.'/../database/migrations/' => base_path('database/migrations')
        ]);
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(__DIR__.'/../config/meta.php', 'meta');
    }

}

<?php namespace Coreplex\Meta;

use Illuminate\Support\ServiceProvider;

class MetaServiceProvider extends ServiceProvider {

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        // Set the files to publish
        $this->publishes([
            __DIR__.'/../config/meta.php' => config_path('meta.php'),
            __DIR__.'/../config/drivers.php' => config_path('drivers.php'),
            __DIR__.'/../database/migrations/' => base_path('database/migrations')
        ]);
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(__DIR__.'/../config/meta.php', 'meta');
        $this->mergeConfigFrom(__DIR__.'/../config/drivers.php', 'drivers');
    }

}

Update Service Provider to include drivers cofnig


<?php

namespace Hicoria\Xpay;

use Nette\Object;

class XpaySmsDispatcher extends Object {

    /**
     * @var IMessageProcessor[]
     */
    private $processors;

    public function register($regex, IMessageProcessor $processor) {
        $this->processors[$regex] = $processor;
    }

    public function process(XpayMessageEntity $paymentEntity) {
        foreach($this->getProcessors() as $regexp => $processor) {
            $success = preg_match_all("~" . preg_replace("/~/", "\\~", $regexp) . "~", $paymentEntity->getModified(), $matches);

            // drop first element - we want matches in parentheses
            array_shift($matches);

            // continue for both, error and no match
            if(!$success)
                return $success;

            $processor->process($matches);

            break;
        }

        return true;
    }

    /**
     * @return \Hicoria\Xpay\IMessageProcessor[]
     */
    public function getProcessors()
    {
        return $this->processors;
    }
}

<?php

namespace Hicoria\Xpay;

use Nette\Object;

class XpaySmsDispatcher extends Object {

    /**
     * @var IMessageProcessor[]
     */
    private $processors;

    public function register($regex, IMessageProcessor $processor) {
        $this->processors[$regex] = $processor;
    }

    public function process(XpayMessageEntity $paymentEntity) {
        foreach($this->getProcessors() as $regexp => $processor) {
            $success = preg_match_all("~" . preg_replace("/~/", "\\~", $regexp) . "~", $paymentEntity->getModified(), $matches);

            // drop first element - we want matches in parentheses
            array_shift($matches);

            // continue for both, error and no match
            if(!$success)
                return $success;

            $processor->process($paymentEntity, $matches);

            break;
        }

        return true;
    }

    /**
     * @return \Hicoria\Xpay\IMessageProcessor[]
     */
    public function getProcessors()
    {
        return $this->processors;
    }
}

Send XpayMessageEntity to process() method


<?php

namespace Tests\PHPExif\Adapter\Native\Reader\Mapper\Exif;

use Mockery as m;
use PHPExif\Adapter\Native\Reader\Mapper\Exif\ApertureFieldMapper;
use PHPExif\Common\Data\ValueObject\Exif\Aperture;

/**
 * Class: ApertureFieldMapperTest
 *
 * @see \PHPUnit_Framework_TestCase
 * @coversDefaultClass \PHPExif\Adapter\Native\Reader\Mapper\Exif\ApertureFieldMapper
 * @covers ::<!public>
 */
class ApertureFieldMapperTest extends BaseFieldMapperTest
{
    /**
     * FQCN of the fieldmapper being tested
     *
     * @var mixed
     */
    protected $fieldMapperClass = ApertureFieldMapper::class;

    /**
     * List of supported fields
     *
     * @var array
     */
    protected $supportedFields = [
        Aperture::class,
    ];

    /**
     * Valid input data
     *
     * @var array
     */
    protected $validInput = [
        'COMPUTED' => [
            'ApertureFNumber' => 'f/5.6',
        ],
    ];
}

<?php

namespace Tests\PHPExif\Adapter\Native\Reader\Mapper\Exif;

use Mockery as m;
use PHPExif\Adapter\Native\Reader\Mapper\Exif\ApertureFieldMapper;
use PHPExif\Common\Data\Exif;
use PHPExif\Common\Data\ValueObject\Exif\Aperture;

/**
 * Class: ApertureFieldMapperTest
 *
 * @see \PHPUnit_Framework_TestCase
 * @coversDefaultClass \PHPExif\Adapter\Native\Reader\Mapper\Exif\ApertureFieldMapper
 * @covers ::<!public>
 */
class ApertureFieldMapperTest extends BaseFieldMapperTest
{
    /**
     * FQCN of the fieldmapper being tested
     *
     * @var mixed
     */
    protected $fieldMapperClass = ApertureFieldMapper::class;

    /**
     * List of supported fields
     *
     * @var array
     */
    protected $supportedFields = [
        Aperture::class,
    ];

    /**
     * Valid input data
     *
     * @var array
     */
    protected $validInput = [
        'COMPUTED' => [
            'ApertureFNumber' => 'f/5.6',
        ],
    ];

    /**
     * @covers ::mapField
     * @group mapper
     *
     * @return void
     */
    public function testMapFieldHasDataInOutput()
    {
        $field = reset($this->supportedFields);
        $output = new Exif;
        $mapper = new $this->fieldMapperClass();

        $originalData = $output->getAperture();
        $mapper->mapField($field, $this->validInput, $output);
        $newData = $output->getAperture();

        $this->assertNotSame($originalData, $newData);

        $this->assertInstanceOf(
            Aperture::class,
            $newData
        );

        $this->assertEquals(
            $this->validInput['COMPUTED']['ApertureFNumber'],
            (string) $newData
        );
    }
}

Check if data is correctly set on Aperture object

Signed-off-by: Tom Van Herreweghe <96835dd8bfa718bd6447ccc87af89ae1675daeca@theanalogguy.be>


<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Inertia\Inertia;

class RegisteredUserController extends Controller
{
    /**
     * Display the registration view.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        return Inertia::render('Auth/Register', [
            'status' => session('errors') ? session('errors')->default->messages() : false
        ]);
    }

    /**
     * Handle an incoming registration request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|confirmed|min:8',
        ]);

        Auth::login($user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]));

        event(new Registered($user));

        return redirect(RouteServiceProvider::HOME);
    }
}

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Inertia\Inertia;

class RegisteredUserController extends Controller
{
    /**
     * Display the registration view.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        return Inertia::render('Auth/Register', [
            'status' => session('errors') ? session('errors')->default->messages() : false
        ]);
    }

    /**
     * Handle an incoming registration request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\RedirectResponse
     *
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|confirmed|min:8',
        ]);

        Auth::login($user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password),
        ]));

        $user->assignRole('user');

        event(new Registered($user));

        return redirect(RouteServiceProvider::HOME);
    }
}

Set user as the default role for new accounts


<?php
class Infusionsoft_AppPool{
	static protected $apps = array();

	public function __construct(){

	}

	public static function getApp($appHostname = ''){
		$appKey = strtolower($appHostname);
		if($appKey == '') $appKey = 'default';
		if(array_key_exists($appKey, self::$apps)){
			return self::$apps[$appKey];
		}
		else{
			return null;
		}
	}

	public static function addApp($app, $appKey = null){
		if(count(self::$apps) == 0){
			self::$apps['default'] = $app;
		}
		if($appKey == null){
			$appKey = $app->getHostname();
		}
		self::$apps[$appKey] = $app;
        return $app;
	}

    public static function clearApps(){
        self::$apps = array();
    }
}

<?php
class Infusionsoft_AppPool{
	static protected $apps = array();

	public function __construct(){

	}

    /**
     * @param string $appHostname
     * @return Infusionsoft_App
     */
    public static function getApp($appHostname = ''){
		$appKey = strtolower($appHostname);
		if($appKey == '') $appKey = 'default';
		if(array_key_exists($appKey, self::$apps)){
			return self::$apps[$appKey];
		}
		else{
			return null;
		}
	}

	public static function addApp($app, $appKey = null){
		if(count(self::$apps) == 0){
			self::$apps['default'] = $app;
		}
		if($appKey == null){
			$appKey = $app->getHostname();
		}
		self::$apps[$appKey] = $app;
        return $app;
	}

    public static function clearApps(){
        self::$apps = array();
    }
}

Add comments to getApp for autocomplete

Add comments to getApp for autocomplete


<?php
require_once('./conf.php');

$sql =
	"SELECT type, sum(cnt) as sumcnt FROM (
		select
		    useragent,
		    (SELECT count(*) FROM log WHERE useragent_id=useragent.id) as cnt,
		    (CASE
		     	WHEN useragent LIKE '%Linux%' THEN 'Linux'
		     	WHEN useragent LIKE '%Macintosh%' THEN 'Macintosh'
		     	WHEN useragent LIKE '%Windows%' THEN 'Windows'
		     	WHEN useragent LIKE 'CloogleBot' THEN 'CloogleBot'
		     	WHEN useragent LIKE 'vim-clean' THEN 'vim-clean'
		     	WHEN useragent LIKE 'cloogle-cli' THEN 'cloogle-cli'
		     	WHEN useragent LIKE 'CloogleMail' THEN 'CloogleMail'
		     	WHEN useragent LIKE 'cloogle-irc' THEN 'cloogle-irc'
		     	ELSE 'Other'
		     END) as type
		FROM useragent
		ORDER BY cnt DESC
	) counts
	GROUP BY type
	ORDER BY sumcnt DESC";

$stmt = $db->stmt_init();
if (!$stmt->prepare($sql))
	var_dump($stmt->error);
$stmt->execute();
$stmt->bind_result($type, $count);

$results = [];
while ($stmt->fetch())
	$results[] = ['name' => $type, 'y' => (int) $count];

$stmt->close();

header('Content-Type: text/javascript');
echo "$callback(" . json_encode($results) . ");";

<?php
require_once('./conf.php');

$sql =
	"SELECT type, sum(cnt) as sumcnt FROM (
		select
			useragent,
			(SELECT count(*) FROM log
				WHERE useragent_id=useragent.id AND
				`responsecode` <> " . E_DOSPROTECT . " AND
				`date` BETWEEN timestamp('$startTime') AND timestamp('$endTime')) as cnt,
			(CASE
				WHEN useragent LIKE '%Linux%' THEN 'Linux'
				WHEN useragent LIKE '%Macintosh%' THEN 'Macintosh'
				WHEN useragent LIKE '%Windows%' THEN 'Windows'
				WHEN useragent LIKE 'CloogleBot' THEN 'CloogleBot'
				WHEN useragent LIKE 'vim-clean' THEN 'vim-clean'
				WHEN useragent LIKE 'cloogle-cli' THEN 'cloogle-cli'
				WHEN useragent LIKE 'CloogleMail' THEN 'CloogleMail'
				WHEN useragent LIKE 'cloogle-irc' THEN 'cloogle-irc'
				ELSE 'Other'
			END) as type
		FROM useragent
		ORDER BY cnt DESC
	) counts
	GROUP BY type
	ORDER BY sumcnt DESC";

$stmt = $db->stmt_init();
if (!$stmt->prepare($sql))
	var_dump($stmt->error);
$stmt->execute();
$stmt->bind_result($type, $count);

$results = [];
while ($stmt->fetch())
	$results[] = ['name' => $type, 'y' => (int) $count];

$stmt->close();

header('Content-Type: text/javascript');
echo "$callback(" . json_encode($results) . ");";

Make OS pie chart aware of dates

Make OS pie chart aware of dates


<?php
namespace Imbo\Plugin\MetadataCache\Cache;

use PHPUnit_Framework_TestCase;

abstract class CacheTests extends PHPUnit_Framework_TestCase {
    /**
     * @var CacheInterface
     */
    private $adpter;

    abstract protected function getAdapter();

    public function setUp() {
        $this->adapter = $this->getAdapter();
    }

    public function getCacheData() {
        return [
            ['key1', 'value'],
            ['key2', 123],
            ['key3', [1, 2, 3]],
            ['key4', new \stdClass()],
        ];
    }

    /**
     * @dataProvider getCacheData
     */
    public function testSetGetAndDelete($key, $value) {
        $this->assertFalse($this->adapter->get($key));
        $this->adapter->set($key, $value);
        $this->assertEquals($value, $this->adapter->get($key));
        $this->assertTrue($this->adapter->delete($key));
        $this->assertFalse($this->adapter->get($key));
    }
}

<?php
namespace Imbo\Plugin\MetadataCache\Cache;

use PHPUnit_Framework_TestCase;
use stdClass;

abstract class CacheTests extends PHPUnit_Framework_TestCase {
    /**
     * @var CacheInterface
     */
    private $adpter;

    /**
     * Get the adapter to test
     *
     * @return CacheInterface
     */
    abstract protected function getAdapter();

    /**
     * Data provider
     *
     * @return array[]
     */
    public function getCacheData() {
        return [
            'string value' => [
                'key' => 'key1',
                'value' => 'value',
            ],
            'numeric value' => [
                'key' => 'key2',
                'value' => 123,
            ],
            'list value' => [
                'key' => 'key3',
                'value' => [1, 2, 3],
            ],
            'object value' => [
                'key' => 'key4',
                'value' => new stdClass(),
            ],
        ];
    }

    /**
     * @dataProvider getCacheData
     * @param string $key The cache key
     * @param mixed $value The cache value
     * @covers ::__construct
     * @covers ::get
     * @covers ::set
     * @covers ::delete
     */
    public function testSetGetAndDelete($key, $value) {
        $adapter = $this->getAdapter();

        $this->assertFalse(
            $adapter->get($key),
            'Cache retrieval should return boolean false'
        );
        $this->assertTrue(
            $adapter->set($key, $value),
            'Cache storage should return boolean true'
        );
        $this->assertEquals(
            $value,
            $adapter->get($key),
            'Incorrect value return from cache'
        );
        $this->assertTrue(
            $adapter->delete($key),
            'Cache deletion should return boolean false'
        );
        $this->assertFalse(
            $adapter->get($key),
            'Value does not seem to have been removed from cache'
        );
    }
}

Add missing phpdoc and improve assertion error messages


<?php

namespace OpenOrchestra\ElasticaAdmin\DisplayBlock;

use OpenOrchestra\DisplayBundle\DisplayBlock\Strategies\AbstractStrategy;
use OpenOrchestra\ModelInterface\Model\ReadBlockInterface;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class ElasticaSearchStrategy
 */
class ElasticaSearchStrategy extends AbstractStrategy
{
    /**
     * Check if the strategy support this block
     *
     * @param ReadBlockInterface $block
     *
     * @return boolean
     */
    public function support(ReadBlockInterface $block)
    {
        return in_array($block->getComponent(), array ('elastica_search', 'elastica_list'));
    }

    /**
     * Perform the show action for a block
     *
     * @param ReadBlockInterface $block
     *
     * @return Response
     */
    public function show(ReadBlockInterface $block)
    {
        return $this->render('OpenOrchestraElasticaAdminBundle:Block/Search:show.html.twig', array(
            'id' => $block->getId(),
            'class' => $block->getClass(),
        ));
    }

    /**
     * Get the name of the strategy
     *
     * @return string
     */
    public function getName()
    {
        return 'elastica_search';
    }
}

<?php

namespace OpenOrchestra\ElasticaAdmin\DisplayBlock;

use OpenOrchestra\DisplayBundle\DisplayBlock\Strategies\AbstractStrategy;
use OpenOrchestra\ModelInterface\Model\ReadBlockInterface;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class ElasticaSearchStrategy
 */
class ElasticaSearchStrategy extends AbstractStrategy
{
    /**
     * Check if the strategy support this block
     *
     * @param ReadBlockInterface $block
     *
     * @return boolean
     */
    public function support(ReadBlockInterface $block)
    {
        return in_array($block->getComponent(), array ('elastica_search', 'elastica_list'));
    }

    /**
     * Perform the show action for a block
     *
     * @param ReadBlockInterface $block
     *
     * @return Response
     */
    public function show(ReadBlockInterface $block)
    {
        return $this->render('OpenOrchestraElasticaAdminBundle:Block/Search:show.html.twig', array(
            'id' => $block->getId(),
            'class' => $block->getClass(),
        ));
    }

    /**
     * @param ReadBlockInterface $block
     *
     * @return Array
     */
    public function getCacheTags(ReadBlockInterface $block)
    {
        return array();
    }

    /**
     * Get the name of the strategy
     *
     * @return string
     */
    public function getName()
    {
        return 'elastica_search';
    }
}

Move getCacheTags from AbstractStrategy to implementing strategies


<?php

namespace Common\Core\Twig\Extensions;

use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

final class IncludeOnceExtension extends AbstractExtension
{
    /** @var array */
    private $includedTemplates = [];

    public function getFunctions(): array
    {
        return [
            new TwigFunction(
                'include_once',
                [$this, 'includeOnce'],
                ['needs_environment' => true, 'needs_context' => true, 'is_safe' => ['all']]
            ),
        ];
    }

    public function includeOnce(
        Environment $env,
        array $context,
        string $template,
        array $variables = [],
        bool $withContext = true,
        bool $ignoreMissing = false,
        bool $sandboxed = false
    ): string {

        if (array_key_exists($template, $this->includedTemplates)) {
            return '';
        }

        $this->includedTemplates[$template] = true;

        return twig_include($env, $context, $template, $variables, $withContext, $ignoreMissing, $sandboxed);
    }
}

<?php

namespace Common\Core\Twig\Extensions;

use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

final class IncludeOnceExtension extends AbstractExtension
{
    /** @var array */
    private $includedTemplates = [];

    public function getFunctions(): array
    {
        return [
            new TwigFunction(
                'include_once',
                [$this, 'includeOnce'],
                ['needs_environment' => true, 'needs_context' => true, 'is_safe' => ['all']]
            ),
            new TwigFunction(
                'is_included',
                [$this, 'isIncluded']
            ),
        ];
    }

    public function includeOnce(
        Environment $env,
        array $context,
        string $template,
        array $variables = [],
        bool $withContext = true,
        bool $ignoreMissing = false,
        bool $sandboxed = false
    ): string {
        if ($this->isIncluded($template)) {
            return '';
        }

        $this->includedTemplates[$template] = true;

        return twig_include($env, $context, $template, $variables, $withContext, $ignoreMissing, $sandboxed);
    }

    public function isIncluded(string $template): bool
    {
        return array_key_exists($template, $this->includedTemplates);
    }
}

Add twig function is_included to check if a templace that can only be included once is alreayd included


<?php declare(strict_types=1);
/* (c) Anton Medvedev <anton@medv.io>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Deployer\Exception;

use Throwable;

class Exception extends \Exception
{
    private static $taskSourceLocation;
    private $taskFilename;
    private $taskLineNumber;

    public function __construct(string $message = "", int $code = 0, Throwable $previous = null)
    {
        if (function_exists('debug_backtrace')) {
            $trace = debug_backtrace();
            foreach ($trace as $t) {
                if (!empty($t['file']) && $t['file'] === self::$taskSourceLocation) {
                    $this->taskFilename = basename($t['file']);
                    $this->taskLineNumber = $t['line'];
                    break;
                }
            }
        }
        parent::__construct($message, $code, $previous);
    }

    public static function setTaskSourceLocation(string $filepath): void
    {
        self::$taskSourceLocation = $filepath;
    }

    public function getTaskFilename(): string
    {
        return $this->taskFilename;
    }

    public function getTaskLineNumber(): int
    {
        return $this->taskLineNumber;
    }

    public function setTaskFilename(string $taskFilename): void
    {
        $this->taskFilename = $taskFilename;
    }

    public function setTaskLineNumber(int $taskLineNumber): void
    {
        $this->taskLineNumber = $taskLineNumber;
    }
}

<?php declare(strict_types=1);
/* (c) Anton Medvedev <anton@medv.io>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Deployer\Exception;

use Throwable;

class Exception extends \Exception
{
    private static $taskSourceLocation = '';
    private $taskFilename = '';
    private $taskLineNumber = '';

    public function __construct(string $message = "", int $code = 0, Throwable $previous = null)
    {
        if (function_exists('debug_backtrace')) {
            $trace = debug_backtrace();
            foreach ($trace as $t) {
                if (!empty($t['file']) && $t['file'] === self::$taskSourceLocation) {
                    $this->taskFilename = basename($t['file']);
                    $this->taskLineNumber = $t['line'];
                    break;
                }
            }
        }
        parent::__construct($message, $code, $previous);
    }

    public static function setTaskSourceLocation(string $filepath): void
    {
        self::$taskSourceLocation = $filepath;
    }

    public function getTaskFilename(): string
    {
        return $this->taskFilename;
    }

    public function getTaskLineNumber(): int
    {
        return $this->taskLineNumber;
    }

    public function setTaskFilename(string $taskFilename): void
    {
        $this->taskFilename = $taskFilename;
    }

    public function setTaskLineNumber(int $taskLineNumber): void
    {
        $this->taskLineNumber = $taskLineNumber;
    }
}

Make exception task filename to be empty string by default


<?php
namespace tests;

use PHPUnit\Framework\TestCase;
use SD\Currency\DependencyInjection\CurrencyProvider;
use SD\Currency\Repository;
use SD\DependencyInjection\Container;

class CurrencyProviderTest extends TestCase {
    public function testConnect() {
        $container = new Container();
        $provider = new CurrencyProvider();
        $container->connect($provider);
        $service = $container->get($provider->getServiceName());
        $this->assertInstanceOf(Repository::class, $service, 'Must return instance of Repository');
    }
}

<?php
namespace tests;

use PHPUnit\Framework\TestCase;
use SD\Currency\DependencyInjection\CurrencyProvider;
use SD\Currency\Repository;
use SD\Currency\Store\ArrayStore;
use SD\DependencyInjection\Container;

class CurrencyProviderTest extends TestCase
{
    public function testConnect()
    {
        $container = new Container();
        $provider = new CurrencyProvider();
        $container->connect($provider);
        $repository = $container->get($provider->getServiceName());
        $this->assertInstanceOf(Repository::class, $repository, 'Must return instance of Repository');
    }

    public function testStoreFromConfig()
    {
        $container = new Container([
            'config' => [
                'currency' => [
                    'store' => [
                        'class' => ArrayStore::class,
                    ],
                ],
            ],
        ]);
        $provider = new CurrencyProvider();
        $container->connect($provider);
        $repository = $container->get($provider->getServiceName());
        $store = $repository->getStore();
        $this->assertInstanceOf(ArrayStore::class, $store, 'Store MUST be an instance of configured class');
    }
}

Add red test for store config

Add red test for store config


<?php

use PragmaRX\Tracker\Support\Migration;

class FixAgentName extends Migration
{
    /**
     * Table related to this migration.
     *
     * @var string
     */
    private $table = 'tracker_agents';

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function migrateUp()
    {
        try {
            $this->builder->table(
                $this->table,
                function ($table) {
                    $table->dropUnique('tracker_agents_name_unique');
                }
            );

            $this->builder->table(
                $this->table,
                function ($table) {
                    $table->mediumText('name')->unique()->change();
                }
            );
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function migrateDown()
    {
        try {
            $this->builder->table(
                $this->table,
                function ($table) {
                    $table->string('name', 255)->change();
                    $table->unique('name');
                }
            );
        } catch (\Exception $e) {
        }
    }
}

<?php

use PragmaRX\Tracker\Support\Migration;

class FixAgentName extends Migration
{
    /**
     * Table related to this migration.
     *
     * @var string
     */
    private $table = 'tracker_agents';

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function migrateUp()
    {
        try {
            $this->builder->table(
                $this->table,
                function ($table) {
                    $table->dropUnique('tracker_agents_name_unique');
                }
            );

            $this->builder->table(
                $this->table,
                function ($table) {
                    $table->mediumText('name')->change();
                }
            );

            $this->builder->table(
                $this->table,
                function ($table) {
                    $table->unique('id', 'tracker_agents_name_unique'); // this is a dummy index
                }
            );
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function migrateDown()
    {
        try {
            $this->builder->table(
                $this->table,
                function ($table) {
                    $table->string('name', 255)->change();
                    $table->unique('name');
                }
            );
        } catch (\Exception $e) {
        }
    }
}

Create a dummy index with the same name

Create a dummy index with the same name


<?php
 /**
 * This file is part of the Certificationy web platform.
 * (c) Johann Saunier (johann_27@hotmail.fr)
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 **/

namespace Gundam\Component\Github;

final class Events
{
    const PULL_REQUEST = 'pull_request';
    const PING = 'ping';
    const PUSH = 'push';
}

<?php
 /**
 * This file is part of the Certificationy web platform.
 * (c) Johann Saunier (johann_27@hotmail.fr)
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 **/

namespace Gundam\Component\Github;

final class Events
{
    const PULL_REQUEST = 'pull_request';
    const PING = 'ping';
    const PUSH = 'push';
    const DELETE = 'delete';
    const DEPLOYMENT = 'deployment';
    const COMMIT_COMMENT = 'commit_comment';
    const ISSUE_COMMENT = 'issue_comment';
    const FORK = 'fork';
    const MEMBER = 'member';
    const RELEASE = 'release';
    const PAGE_BUILD = 'page_build';
    const CREATE = 'create';
    const STATUS = 'status';
    const DEPLOYMENT_STATUS = 'deployment_status';
    const PULL_REQUEST_REVIEW_COMMENT = 'pull_request_review_comment';
    const ISSUES = 'issues';
    const WATCH = 'watch';
    const VISIBILITY = 'public';
    const TEAM_ADD = 'team_add';
    const GOLLUM = 'gollum';
}

Add github event on gundam

Add github event on gundam


<?php
/**
 * @category   Sales
 * @package    Quafzi_NoAutoInvoice
 * @license    MIT
 * @author     Thomas Birke <tbirke@netextreme.de>
 */
class Quafzi_NoAutoInvoice_Helper_Data extends Mage_Core_Helper_Abstract
{
    /**
     * if user wants to create an invoice manually
     *
     * @return bool
     */
    public function isManualInvoiceCreation()
    {
        $allowedControllerNames = ['sales_order_invoice', 'sales_order_creditmemo'];
        return (Mage::app()->getRequest()
            && 'save' === Mage::app()->getRequest()->getActionName()
            && in_array(Mage::app()->getRequest()->getControllerName(), $allowedControllerNames)
        );
    }

    /**
     * if auto-invoicing is allowed for given country
     *
     * @param int $countryId Country ID (e.g. "DE")
     * @return bool
     */
    public function isInvoicingAllowed ($countryId)
    {
        $allowedCountryIds = explode(',', Mage::getStoreConfig('sales/invoice/autocreation_countries'));
        return $this->isManualInvoiceCreation() || in_array($countryId, $allowedCountryIds);
    }
}

<?php
/**
 * @category   Sales
 * @package    Quafzi_NoAutoInvoice
 * @license    MIT
 * @author     Thomas Birke <tbirke@netextreme.de>
 */
class Quafzi_NoAutoInvoice_Helper_Data extends Mage_Core_Helper_Abstract
{
    /**
     * if user wants to create an invoice manually
     *
     * @return bool
     */
    public function isManualInvoiceCreation()
    {
        $allowedControllerNames = ['sales_order_invoice', 'sales_order_creditmemo', 'sales_order_shipment'];
        return (Mage::app()->getRequest()
            && 'save' === Mage::app()->getRequest()->getActionName()
            && in_array(Mage::app()->getRequest()->getControllerName(), $allowedControllerNames)
        );
    }

    /**
     * if auto-invoicing is allowed for given country
     *
     * @param int $countryId Country ID (e.g. "DE")
     * @return bool
     */
    public function isInvoicingAllowed ($countryId)
    {
        $allowedCountryIds = explode(',', Mage::getStoreConfig('sales/invoice/autocreation_countries'));
        return $this->isManualInvoiceCreation() || in_array($countryId, $allowedCountryIds);
    }
}

Add sales_order_shipment to list of allowed controller actions


<?php

namespace adrianclay\git\Pack;

use adrianclay\git\Repository;
use adrianclay\git\SHA;
use PHPUnit\Framework\TestCase;

class IndexTest extends TestCase
{
    private $repository;

    public function setUp(): void
    {
        parent::setUp();
        $path = __DIR__ . '/../../';
        $this->repository = new Repository( $path );
    }

    public function testCanGetAOffsetOfZeroPrefixedSha() {
        $sha = new SHA( "00" . "f5270dc9fcb8ec4c31e04334128a4a9f596470" );
        $object = $this->repository->getObject( $sha );
        $this->assertNotNull( $object );
    }
}

<?php

namespace adrianclay\git\Pack;

use adrianclay\git\Repository;
use adrianclay\git\SHA;
use PHPUnit\Framework\TestCase;

class IndexTest extends TestCase
{
    private $repository;

    public function setUp(): void
    {
        parent::setUp();
        $path = __DIR__ . '/../../';
        $this->repository = new Repository( $path );
    }

    public function testCanGetAOffsetOfZeroPrefixedSha() {
        $sha = new SHA( "00" . "f5270dc9fcb8ec4c31e04334128a4a9f596470" );
        $object = $this->repository->getObject( $sha );
        $this->assertNotNull( $object );
    }

    public function testGivenPhpFileThrowsInvalidException() {
        $this->expectException(\InvalidArgumentException::class);

        new Index(__FILE__);
    }
}

Add test for magic value check

Add test for magic value check


<?php
namespace CodeDay\Clear\Controllers\Api;

use \CodeDay\Clear\Models;

class Events extends ContractualController {
    protected $fields = [
        'id',
        'name',
        'full_name',
        'registration_info' => [
            'estimate' => 'registration_estimate',
            'max' => 'max_registrations',
            'is_open' => 'allow_registrations'
        ],
        'venue',
        'starts_at',
        'ends_at',
        'batch_name',
        'waiver' => 'waiver_link',
        'manager' => 'manager_username'
    ];

    public function getIndex()
    {
        return $this->getContract(Models\Batch::Loaded()->events);
    }

    public function getEvent()
    {
        return $this->getContract(\Route::input('event'));
    }
}

<?php
namespace CodeDay\Clear\Controllers\Api;

use \CodeDay\Clear\Models;

class Events extends ContractualController {
    protected $fields = [
        'id',
        'name',
        'webname',
        'abbr',
        'full_name',
        'registration_info' => [
            'estimate' => 'registration_estimate',
            'max' => 'max_registrations',
            'is_open' => 'allow_registrations'
        ],
        'venue',
        'starts_at',
        'ends_at',
        'batch_name',
        'waiver' => 'waiver_link',
        'manager' => 'manager_username'
    ];

    public function getIndex()
    {
        return $this->getContract(Models\Batch::Loaded()->events);
    }

    public function getEvent()
    {
        return $this->getContract(\Route::input('event'));
    }
}

Add webname in event model

Add webname in event model


<?php

class Meanbee_ShoppingAssistant_Model_Resource_Request extends Mage_Core_Model_Resource_Db_Abstract
{
    public function _construct()
    {
        $this->_init("meanbee_shoppingassistant/request", "entity_id");
    }
}

<?php

class Meanbee_ShoppingAssistant_Model_Resource_Request extends Mage_Core_Model_Resource_Db_Abstract
{
    public function _construct()
    {
        $this->_init("meanbee_shoppingassistant/request", "entity_id");
    }

    protected function _prepareDataForSave(Mage_Core_Model_Abstract $object)
    {
        if ((!$object->getId() || $object->isObjectNew()) && !$object->getCreatedAt()) {
            $object->setCreatedAt($this->formatDate(true));
        }
        return parent::_prepareDataForSave($object);
    }

}

Set a created_at date before saving a new request


<?php

namespace Festitime\DatabaseBundle\Repository;

use Doctrine\ODM\MongoDB\DocumentRepository;

/**
 * UserRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class UserRepository extends DocumentRepository
{
}

Add empty line at the end

Add empty line at the end