<?php
namespace CFPropertyList;

require_once( 'cfpropertylist-2.0.1/CFPropertyList.php' );

// Get the varibles passed by the enroll script
$identifier         = $_GET["identifier"];
$hostname           = $_GET["hostname"];

// Split the manifest path up to determine directory structure
$directories        = explode( "/", $identifier, -1 );
$total              = count( $directories );
$n                  = 0;
$identifier_path    = "";
while ( $n < $total )
    {
        $identifier_path .= $directories[$n] . '/';
        $n++;
    }

// Check if manifest already exists for this machine
if ( file_exists( '../manifests/' . $identifier_path . '/clients/' . $hostname ) )
    {
        echo "Computer manifest already exists.";
    }
else
    {
        echo "Computer manifest does not exist. Will create.";

        if ( !is_dir( '../manifests/' . $identifier_path . 'clients/' ) )
            {
                mkdir( '../manifests/' . $identifier_path . 'clients/', 0755, true );
            }

        // Create the new manifest plist
        $plist = new CFPropertyList();
        $plist->add( $dict = new CFDictionary() );

        // Add manifest to production catalog by default
        $dict->add( 'catalogs', $array = new CFArray() );
        $array->add( new CFString( 'production' ) );

        // Add parent manifest to included_manifests to achieve waterfall effect
        $dict->add( 'included_manifests', $array = new CFArray() );
        $array->add( new CFString( $identifier ) );

        // Save the newly created plist
        $plist->saveXML( '../manifests/' . $identifier_path . 'clients/' . $hostname );

    }

?>

<?php
namespace CFPropertyList;

require_once( 'cfpropertylist-2.0.1/CFPropertyList.php' );

// Get the varibles passed by the enroll script
$identifier         = $_GET["identifier"];
$hostname           = $_GET["hostname"];

// Check if manifest already exists for this machine
if ( file_exists( '../manifests/' . $hostname ) )
{
	echo "Computer manifest already exists.";
}
else
{
	echo "Computer manifest does not exist. Will create.";

	// Create the new manifest plist
	$plist = new CFPropertyList();
	$plist->add( $dict = new CFDictionary() );

	// Add manifest to production catalog by default
	$dict->add( 'catalogs', $array = new CFArray() );
	$array->add( new CFString( 'production' ) );

	// Add parent manifest to included_manifests to achieve waterfall effect
	$dict->add( 'included_manifests', $array = new CFArray() );
	$array->add( new CFString( $identifier ) );

	// Save the newly created plist
	$plist->saveXML( '../manifests/' . $hostname );
}
?>

Remove code to support manifest sub-directories that we will not be using


<?php declare(strict_types = 1);

use Nette\Configurator;

require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/TestCase.php';
require_once __DIR__ . '/PHPStan/Rules/AbstractRuleTest.php';
require_once __DIR__ . '/PHPStan/Rules/AlwaysFailRule.php';
require_once __DIR__ . '/PHPStan/Rules/DummyRule.php';

$rootDir = __DIR__ . '/..';
$tmpDir = $rootDir . '/tmp';
$confDir = $rootDir . '/conf';

$configurator = new Configurator();
$configurator->defaultExtensions = [];
$configurator->setDebugMode(true);
$configurator->setTempDirectory($tmpDir);
$configurator->addConfig($confDir . '/config.neon');
$configurator->addConfig($confDir . '/config.level5.neon');
$configurator->addParameters([
	'rootDir' => $rootDir,
	'tmpDir' => $tmpDir,
	'currentWorkingDirectory' => $rootDir,
	'cliArgumentsVariablesRegistered' => false,
]);
$container = $configurator->createContainer();

PHPStan\TestCase::setContainer($container);
PHPStan\Type\TypeCombinator::setUnionTypesEnabled(true);
require_once __DIR__ . '/phpstan-bootstrap.php';

<?php declare(strict_types = 1);

use Nette\Configurator;

require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/TestCase.php';
require_once __DIR__ . '/PHPStan/Rules/AbstractRuleTest.php';
require_once __DIR__ . '/PHPStan/Rules/AlwaysFailRule.php';
require_once __DIR__ . '/PHPStan/Rules/DummyRule.php';

$rootDir = __DIR__ . '/..';
$tmpDir = $rootDir . '/tmp';
$confDir = $rootDir . '/conf';

$configurator = new Configurator();
$configurator->defaultExtensions = [];
$configurator->setDebugMode(true);
$configurator->setTempDirectory($tmpDir);
$configurator->addConfig($confDir . '/config.neon');
$configurator->addConfig($confDir . '/config.level7.neon');
$configurator->addParameters([
	'rootDir' => $rootDir,
	'tmpDir' => $tmpDir,
	'currentWorkingDirectory' => $rootDir,
	'cliArgumentsVariablesRegistered' => false,
]);
$container = $configurator->createContainer();

PHPStan\TestCase::setContainer($container);
PHPStan\Type\TypeCombinator::setUnionTypesEnabled(true);
require_once __DIR__ . '/phpstan-bootstrap.php';

Use the highest level in analyser integration tests


@servers(['demo' => 'timegrid'])

@task('check', ['on' => 'demo'])
    cd /var/www/timegrid.io/dev/htdocs
    phpunit
@endtask

@task('deploy', ['on' => 'demo'])
    sudo /usr/local/bin/deploy.sh development
@endtask

@task('seed', ['on' => 'demo'])
    {{-- Target the project directory --}}
    cd /var/www/timegrid.io/demo/htdocs
    {{-- If there is anything to migrate, migrate it --}}
    php artisan db:seed --class="CategoriesSeeder"
@endtask

@task('refresh', ['on' => 'demo'])
    {{-- Target the project directory --}}
    cd /var/www/timegrid.io/dev/htdocs
    {{-- If there is anything to migrate, migrate it --}}
    php artisan migrate:refresh --seed
@endtask

@servers(['moongate' => 'timegrid'])

@task('deploy', ['on' => 'moongate'])
    sudo /usr/local/bin/deploy.sh {{ $environment }}
@endtask

Update deploy process and cleanup

Update deploy process and cleanup


<?php declare(strict_types=1);
namespace Onion\Framework\Collection;

class CallbackCollection extends Collection
{
    /** @var callable */
    private $callback;

    public function __construct(iterable $items, callable $callback)
    {
        if (is_array($items)) {
            $items = new \ArrayIterator($items);
        }

        parent::__construct($items);
        $this->callback = $callback;
    }

    public function current()
    {
        return call_user_func($this->callback, parent::current(), $this->key());
    }
}

<?php declare(strict_types=1);
namespace Onion\Framework\Collection;

class CallbackCollection extends Collection
{
    /** @var callable */
    private $callback;

    public function __construct(iterable $items, callable $callback)
    {
        if (is_array($items)) {
            $items = new \ArrayIterator($items);
        }

        parent::__construct($items);
        $this->callback = $callback;
    }

    public function current()
    {
        return call_user_func($this->callback, $this, $this->key());
    }
}

Return self instead of parent to allow nested resolutions


<?php
interface ISugarCache {
    function stamp (SugarRef $ref, $type);
    function load (SugarRef $ref, $type);
    function store (SugarRef $ref, $type, $data);
    function erase (SugarRef $ref, $type);
    function clear ();
}

class SugarCacheHandler {
    private $sugar;
    private $output;
    private $bc;

    private function compact () {
        if ($this->output) {
            $this->bc []= 'echo';
            $this->bc []= $this->output;
            $this->output = '';
        }
    }

    public function __construct (&$sugar) {
        $this->sugar =& $sugar;
    }

    public function addOutput ($text) {
        $this->output .= $text;
    }

    public function addCall ($func, $args) {
        $this->compact();
        array_push($this->bc, 'cinvoke', $func, $args);
    }

    public function getOutput () {
        $this->compact();
        return $this->bc;
    }

    public function beginCache () {
        ob_start();
    }

    public function endCache ($ignore = false) {
        if (!$ignore)
            $this->output .= ob_get_contents();
        ob_end_clean();
    }
}
// vim: set expandtab shiftwidth=4 tabstop=4 : ?>

<?php
interface ISugarCache {
    function stamp (SugarRef $ref, $type);
    function load (SugarRef $ref, $type);
    function store (SugarRef $ref, $type, $data);
    function erase (SugarRef $ref, $type);
    function clear ();
}

class SugarCacheHandler {
    private $sugar;
    private $output;
    private $bc;

    private function compact () {
        if ($this->output) {
            $this->bc []= 'echo';
            $this->bc []= $this->output;
            $this->output = '';
        }
    }

    public function __construct (&$sugar) {
        $this->sugar =& $sugar;
    }

    public function addOutput ($text) {
        $this->output .= $text;
    }

    public function addCall ($func, $args) {
        $this->compact();
        array_push($this->bc, 'cinvoke', $func, $args);
    }

    public function addBlock ($block) {
        $this->compact();
        array_push($this->bc, 'nocache', $block);
    }

    public function getOutput () {
        $this->compact();
        return $this->bc;
    }

    public function beginCache () {
        ob_start();
    }

    public function endCache ($ignore = false) {
        if (!$ignore)
            $this->output .= ob_get_contents();
        ob_end_clean();
    }
}
// vim: set expandtab shiftwidth=4 tabstop=4 : ?>

Add a method to store an unmodified block on the bytecode cache.


<?php
namespace AdminAddonRevisions;

class TaskHandler {

  public function __construct($plugin) {
    $this->plugin = $plugin;
    $this->admin = $plugin->grav()['admin'];
    $this->uri = $plugin->grav()['uri'];
  }

  public function execute($method) {
    if (method_exists($this, $method)) {
      return call_user_func([$this, $method]);
    }

    return false;
  }

  public function taskRevDelete() {
    // TODO: Permission

    $rev = $this->uri->param('rev');
    if (!$rev) {
      // TODO: Message
      return false;
    }

    $page = $this->plugin->getCurrentPage();
    $revision = new Revision($page, $rev);
    if (!$revision->exists()) {
      // TODO: Message
      return false;
    }

    $revision->delete();

    return true;
  }

}

<?php
namespace AdminAddonRevisions;

class TaskHandler {

  public function __construct($plugin) {
    $this->plugin = $plugin;
    $this->admin = $plugin->grav()['admin'];
    $this->uri = $plugin->grav()['uri'];
  }

  public function execute($method) {
    if (method_exists($this, $method)) {
      return call_user_func([$this, $method]);
    }

    return false;
  }

  public function taskRevDelete() {
    $messages = $this->plugin->grav()['messages'];
    // TODO: Permission

    $rev = $this->uri->param('rev');
    if (!$rev) {
      $messages->add("Revision param is missing", 'error');
      $this->plugin->grav()->redirect($this->uri->url());
      return false;
    }

    $page = $this->plugin->getCurrentPage();
    $revision = new Revision($page, $rev);
    if (!$revision->exists()) {
      $messages->add("Revision not found", 'error');
      $this->plugin->grav()->redirect($this->uri->url());
      return false;
    }

    $revision->delete();

    $messages->add("Succesfully deleted the '$rev' revision", 'info');
    $this->plugin->grav()->redirect($this->uri->url());

    return true;
  }

  public function taskRevRevert() {
    // TODO: Permission

    $rev = $this->uri->param('rev');
    if (!$rev) {
      // TODO: Message
      return false;
    }

    $page = $this->plugin->getCurrentPage();
    $revision = new Revision($page, $rev);
    if (!$revision->exists()) {
      // TODO: Message
      return false;
    }

    $revision->delete();

    return true;
  }

}

Add messages and redirection to task revDelete


<?php

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

class CreateTagsAndPostTagTables extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tags', function (Blueprint $table) {
            $table->increments('id')->comment('Primary key.');
            $table->string('tag_name');
            $table->string('tag_slug');
            $table->timestamps();
        });

        Schema::create('post_tag', function (Blueprint $table) {
            $table->integer('post_id');
            $table->integer('tag_id');
            $table->primary(['post_id', 'tag_id']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('tags', function (Blueprint $table) {
            Schema::drop('tags');
        });

        Schema::table('post_tag', function (Blueprint $table) {
            Schema::drop('post_tag');
        });
    }
}

<?php

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

class CreateTagsAndPostTagTables extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tags', function (Blueprint $table) {
            $table->increments('id')->comment('Primary key.');
            $table->string('tag_name');
            $table->string('tag_slug');
            $table->timestamps();
        });

        Schema::create('post_tag', function (Blueprint $table) {
            $table->integer('post_id');
            $table->integer('tag_id');
            $table->primary(['post_id', 'tag_id']);
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('tags', function (Blueprint $table) {
            Schema::drop('tags');
        });

        Schema::table('post_tag', function (Blueprint $table) {
            Schema::drop('post_tag');
        });
    }
}

Add timestamps to pivot table

Add timestamps to pivot table


<?php
ini_set("memory_limit","1024M");

chdir(__DIR__);
require_once (__DIR__ . '/../../bootstrap.php');

$permCrit = new Criteria();
$permCrit->add(PermissionPeer::NAME, 'FEATURE_EDGE_SERVER');
$permCrit->add(PermissionPeer::STATUS, PermissionStatus::ACTIVE);
$permCrit->add(PermissionPeer::TYPE, PermissionType::SPECIAL_FEATURE);

$permissions = PermissionPeer::doSelect($permCrit);

foreach ($permissions as $perm)
{
	/* @var $perm Permission */
	$perm->setName("FEATURE_SERVER_NODE");
	$perm->save();
}

<?php
ini_set("memory_limit","1024M");

chdir(__DIR__);
require_once (__DIR__ . '/../../bootstrap.php');

$permCrit = new Criteria();
$permCrit->add(PermissionPeer::NAME, 'FEATURE_EDGE_SERVER');
$permCrit->add(PermissionPeer::STATUS, PermissionStatus::ACTIVE);
$permCrit->add(PermissionPeer::TYPE, PermissionType::SPECIAL_FEATURE);

$permissions = PermissionPeer::doSelect($permCrit);

foreach ($permissions as $perm)
{
	/* @var $perm Permission */
	$newPermission = $perm->copy();
	$newPermission->setName("FEATURE_SERVER_NODE");
	$newPermission->save();
}

Add new permission instead of updating existing one (avoid down time)


<?php namespace app\Helpers\Validators;

use Illuminate\Validation\Validator;

/**
 * Class MainMetaValidator
 *
 * A class to handle validation of main meta
 * updates and creation.
 *
 * @author Rob Attfield <emailme@robertattfield.com> <http://www.robertattfield.com>
 * @package app\Helpers\Validators
 */
class MainMetaValidator extends Validator
{
    public static function validationRules()
    {
        return [
            'title' => 'min:10|max:70',
            'description' => 'min:20|max:160',
            'keywords' => 'min:3|max:255',
            'google_analytics_code' => 'max:20',
            'yandex_verification' => 'max:70',
            'bing_verification' => 'max:70',
            'addthisid' => 'max:35',
            'page_main_title' => 'required|min:15|max:100',
            //'page_main_content' => '',
        ];
    }
}

<?php namespace app\Helpers\Validators;

use Illuminate\Validation\Validator;

/**
 * Class MainMetaValidator
 *
 * A class to handle validation of main meta
 * updates and creation.
 *
 * @author Rob Attfield <emailme@robertattfield.com> <http://www.robertattfield.com>
 * @package app\Helpers\Validators
 */
class MainMetaValidator extends Validator
{
    public static function validationRules()
    {
        return [
            'title' => 'min:10|max:70',
            'description' => 'min:20|max:160',
            'keywords' => 'min:3|max:255',
            'google_analytics_code' => 'max:20',
            'yandex_verification' => 'max:70',
            'bing_verification' => 'max:70',
            'addthisid' => 'max:35',
            'page_main_title' => 'required|min:15|max:100',
        ];
    }
}

Remove hardcoded AddThis ID, made migrations and form changes to store it in database.


<?php
namespace Search\Test\TestCase\Model\Filter;

use Cake\TestSuite\TestCase;
use Search\Manager;
use Search\Model\Filter\Base;

class Filter extends Base
{

    public function process()
    {
    }
}

class BaseTest extends TestCase
{

    public function testSkip()
    {
        $manager = $this->getMock('\Search\Manager', null, [], 'Manager', false);
        $filter = new Filter(
            'field',
            $manager,
            ['alwaysRun' => true, 'filterEmpty' => true]
        );

        $filter->args(['field' => '1']);
        $this->assertFalse($filter->skip());

        $filter->args(['field' => '0']);
        $this->assertFalse($filter->skip());

        $filter->args(['field' => '']);
        $this->assertTrue($filter->skip());

        $filter->args(['field' => []]);
        $this->assertTrue($filter->skip());
    }
}

<?php
namespace Search\Test\TestCase\Model\Filter;

use Cake\TestSuite\TestCase;
use Cake\ORM\TableRegistry;
use Search\Manager;
use Search\Model\Filter\Base;

class Filter extends Base
{

    public function process()
    {
    }
}

class BaseTest extends TestCase
{

    public $fixtures = [
        'plugin.Search.Articles'
    ];

    public function setup()
    {
        $table = TableRegistry::get('Articles');
        $manager = new Manager($table);
        $this->manager = new Manager($table);
    }

    public function testSkip()
    {
        $filter = new Filter(
            'field',
            $this->manager,
            ['alwaysRun' => true, 'filterEmpty' => true]
        );

        $filter->args(['field' => '1']);
        $this->assertFalse($filter->skip());

        $filter->args(['field' => '0']);
        $this->assertFalse($filter->skip());

        $filter->args(['field' => '']);
        $this->assertTrue($filter->skip());

        $filter->args(['field' => []]);
        $this->assertTrue($filter->skip());
    }

    public function testFieldAliasing()
    {
        $filter = new Filter(
            'field',
            $this->manager,
            []
        );

        $this->assertEquals('Articles.field', $filter->field());

        $filter->config('aliasField', false);
        $this->assertEquals('field', $filter->field());

        $filter = new Filter(
            ['field1', 'field2'],
            $this->manager,
            []
        );

        $expected = ['Articles.field1', 'Articles.field2'];
        $this->assertEquals($expected, $filter->field());
    }
}

Add tests for auto field aliasing

Add tests for auto field aliasing


<?php

$language = CM_Model_Language::findByAbbreviation('de');
$language->setTranslation('.internals.role.' . Denkmal_Role::ADMIN, 'Admin');
$language->setTranslation('.internals.role.' . Denkmal_Role::PUBLISHER, 'Publisher');
$language->setTranslation('.internals.role.' . Denkmal_Role::HIPSTER, 'Denkmal Hipster');

if ($userFrederick = Denkmal_Model_User::findByEmail('fred.jan.duerr@gmail.com')) {
    $userFrederick->getRoles()->delete(Denkmal_Role::ADMIN);
    $userFrederick->getRoles()->add(Denkmal_Role::PUBLISHER);
}

Adjust user roles in migration

Adjust user roles in migration


<?php
/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder;

return [
    'up' => function (Builder $schema) {
        $schema->table('users_discussions', function (Blueprint $table) {
            $table->enum('subscription', ['follow', 'ignore'])->nullable();
        });
    },

    'down' => function (Builder $schema) {
        $schema->table('users_discussions', function (Blueprint $table) {
            $table->dropColumn('subscription');
        });
    }
];

<?php
/*
 * This file is part of Flarum.
 *
 * (c) Toby Zerner <toby.zerner@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Flarum\Database\Migration;

return Migration::addColumns('users_discussions', [
    'subscription' => ['enum', 'allowed' => ['follow', 'ignore'], 'nullable' => true]
]);

Use new shortcuts for migrations

Use new shortcuts for migrations


<?php

namespace Mdb\PayPal\Ipn;

class Message
{
    /**
     * @var array
     */
    private $data;

    /**
     * @param array|string $data
     */
    public function __construct($data)
    {
        if (!is_array($data)) {
            $data = $this->extractDataFromRawPostDataString($data);
        }

        $this->data = $data;
    }

    /**
     * @param string $key
     *
     * @return string
     */
    public function get($key)
    {
        $value = '';

        if (isset($this->data[$key])) {
            $value = $this->data[$key];
        }

        return $value;
    }

    /**
     * @return array
     */
    public function getAll()
    {
        return $this->data;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        $str = '';

        foreach ($this->data as $k => $v) {
            $str .= sprintf('%s=%s&', $k, urlencode($v));
        }

        return rtrim($str, '&');
    }

    /**
     * @param string $rawPostDataString
     *
     * @return array
     */
    private function extractDataFromRawPostDataString($rawPostDataString)
    {
        $data = array();
        $keyValuePairs = preg_split('/&/', $rawPostDataString, null, PREG_SPLIT_NO_EMPTY);

        foreach ($keyValuePairs as $keyValuePair) {
            list($k, $v) = explode('=', $keyValuePair);

            $data[$k] = urldecode($v);
        }

        return $data;
    }
}

<?php

namespace Mdb\PayPal\Ipn;

class Message
{
    /**
     * @var array
     */
    private $data;

    /**
     * @param array|string $data
     */
    public function __construct($data)
    {
        if (!is_array($data)) {
            $data = $this->extractDataFromRawPostDataString($data);
        }

        $this->data = $data;
    }

    /**
     * @param string $key
     *
     * @return string
     */
    public function get($key)
    {
        $value = '';

        if (isset($this->data[$key])) {
            $value = $this->data[$key];
        }

        return $value;
    }

    /**
     * @return array
     */
    public function getAll()
    {
        return $this->data;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        $str = '';

        foreach ($this->data as $k => $v) {
            $str .= sprintf('%s=%s&', $k, rawurlencode($v));
        }

        return rtrim($str, '&');
    }

    /**
     * @param string $rawPostDataString
     *
     * @return array
     */
    private function extractDataFromRawPostDataString($rawPostDataString)
    {
        $data = array();
        $keyValuePairs = preg_split('/&/', $rawPostDataString, null, PREG_SPLIT_NO_EMPTY);

        foreach ($keyValuePairs as $keyValuePair) {
            list($k, $v) = explode('=', $keyValuePair);

            $data[$k] = rawurldecode($v);
        }

        return $data;
    }
}

Update to rawurlencode / rawurldecode

Update to rawurlencode / rawurldecode

Due to [this](https://github.com/paypal/ipn-code-samples/issues/51), the listener will *always* return INVALID unless `raw` methods are used for encoding / decoding.


<?php
namespace WiContactAPI\V1\Rest\Contact;

use Zend\Paginator\Paginator;
use Doctrine\ORM\EntityRepository;

class ContactCollection extends EntityRepository
{

}

<?php
namespace WiContactAPI\V1\Rest\Contact;

use DoctrineORMModule\Paginator\Adapter\DoctrinePaginator as PaginatorAdapter;
use Doctrine\ORM\Tools\Pagination\Paginator as ORMPaginator;
use Zend\Paginator\Paginator as ZendPaginator;
use Doctrine\ORM\EntityRepository as EntityRepository;

class ContactCollection extends EntityRepository
{

    /**
     * Custom method to get paged, filtered, ordered data |
     * Método para obtener datos paginados, filtrados y ordenados
     *
     * @param array $params
     * @return  \Zend\Paginator\Paginator
     */
    public function pageBy($params = array())
    {

        // Table alias | Alias para las tablas
        $tbl1 = 'wi_contact';

        // Define fields that allow filtering and ordering |
        // Definir los campos que permiten filtros y ordenación
        $fields = array(
            'id' => $tbl1 . '.id',
            'name' => $tbl1 . '.name'
        );

        // Create query builder | Crear el query builder
        $qb = $this->createQueryBuilder("$tbl1")
            ->select("$tbl1");

        // Add filters | Agregar filtros
        $i = 0;

        // If filters are setted | Si los filtros están definidos
        if (property_exists($params, 'filters')) {

            // Decode filters string | decodificar el string con los filtros
            $filters = json_decode($params->filters);

            // Create each filter in Query | Crear cada filtro en la consulta
            foreach ($filters as $filter => $string) {

                // Check if field allows filtering | Checkear si el campo permite filtrar
                if (array_key_exists($filter, $fields)) {

                    // Count | Contador
                    $i = $i + 1;

                    // Get the field | Cargar el campo a filtrar
                    $field = $fields[$filter];

                    // Clean filter string | Limpiar el texto del filtro
                    // @todo: Ver porqué el underscore no funciona en la búsqueda
                    $string = '%' . preg_replace("/[^a-zA-Z0-9áéíóúüÁÉÍÓÚÜ',.@&_-]+/", "", $string) . '%';

                    // Add Where/like clause with filter | Agregar clausula Where/like con el filtro
                    $qb->andWhere(
                        $qb->expr()->like($field, "?$i")
                    );
                    $qb->setParameter($i, $string);

                } // if
            } // foreach
        } // if

    } // function pageBy

} // class

Add pageBy method to return sorted, filtered, paged data Agregar el método pageBy para obtener datos ordenados, filtrados y paginados


<?php

namespace Shim\Model\Entity;

use Cake\Utility\Inflector;
use RuntimeException;

/**
 * Trait to read/write entity properties in a way that the returned/passed value is ensured (not nullable).
 *
 * - get{PropertyName}OrFail() must return the property or throws exception otherwise
 * - set{PropertyName}OrFail($value) must have a non-null value or throws exception otherwise
 */
trait GetSetTrait {

	use GetTrait;
	use SetTrait;

	/**
	 * @param string $name
	 * @param array $arguments
	 * @throws \RuntimeException
	 * @return mixed
	 */
	public function __call(string $name, array $arguments) {
		if (!preg_match('/^(set|get)([A-Z][A-Za-z0-9]+)OrFail$/', $name, $matches)) {
			throw new RuntimeException('Method ' . $name . ' cannot be found; set{PropertyName}OrFail() expected.');
		}
		if ($matches[1] === 'set' && !$arguments) {
			throw new RuntimeException('Method ' . $name . ' param for value not found, but expected.');
		}

		$property = Inflector::underscore($matches[2]);

		if ($matches[1] === 'get') {
			return $this->getOrFail($property);
		}

		$this->setOrFail($property, $arguments[1]);
	}

}

<?php

namespace Shim\Model\Entity;

use Cake\Utility\Inflector;
use RuntimeException;

/**
 * Trait to read/write entity properties in a way that the returned/passed value is ensured (not nullable).
 *
 * - get{PropertyName}OrFail() must return the property or throws exception otherwise
 * - set{PropertyName}OrFail($value) must have a non-null value or throws exception otherwise
 */
trait GetSetTrait {

	use GetTrait;
	use SetTrait;

	/**
	 * @param string $name
	 * @param array $arguments
	 * @throws \RuntimeException
	 * @return mixed
	 */
	public function __call(string $name, array $arguments) {
		if (!preg_match('/^(set|get)([A-Z][A-Za-z0-9]+)OrFail$/', $name, $matches)) {
			throw new RuntimeException('Method ' . $name . ' cannot be found; set{PropertyName}OrFail() expected.');
		}
		if ($matches[1] === 'set' && !$arguments) {
			throw new RuntimeException('Method ' . $name . ' param for value not found, but expected.');
		}

		$property = Inflector::underscore($matches[2]);

		if ($matches[1] === 'get') {
			return $this->getOrFail($property);
		}

		return $this->setOrFail($property, $arguments[1]);
	}

}

Add set for OrFail functionality.

Add set for OrFail functionality.


<?php

namespace Apixu\Tests;

use Apixu\Apixu;
use Apixu\Config;
use PHPUnit\Framework\TestCase;

class ApixuTest extends TestCase
{
    /**
     * @expectedException \Apixu\Exception\ConfigException
     */
    public function testApiWithMissingApiKey()
    {
        $config = new Config();
        $config->setApiKey(" ");

        Apixu::api($config);
    }
}

<?php

namespace Apixu\Tests;

use Apixu\ApiInterface;
use Apixu\Apixu;
use Apixu\Config;
use PHPUnit\Framework\TestCase;

class ApixuTest extends TestCase
{
    public function testApi()
    {
        $config = new Config();
        $config->setApiKey("apikey");

        $api = Apixu::api($config);
        $this->assertInstanceOf(ApiInterface::class, $api);
    }

    /**
     * @expectedException \Apixu\Exception\ConfigException
     */
    public function testApiWithMissingApiKey()
    {
        $config = new Config();
        $config->setApiKey(" ");

        Apixu::api($config);
    }
}

Add api build test for success case.

Add api build test for success case.


<?php
return [
    'settings' => [
        'debug'=> true,
        'site-name' => 'OpenDock',
        'support-mail' => 'opendock@example.com',
        'source-code' => 'https://github.com/KSP-SpaceDock/OpenDock',
        'irc-channel' => 'http://webchat.esper.net/?channels=spacedock',
        'donation-link' => '',

        'backend-url' => '',
        'gameshort' => '',
        'update-interval' => 30000
    ]
];
?>

<?php
return [
    'settings' => [
        'debug'=> true,
        'site-name' => 'OpenDock',
        'support-mail' => 'opendock@example.com',
        'source-code' => 'https://github.com/KSP-SpaceDock/OpenDock',
        'irc-channel' => 'http://webchat.esper.net/?channels=spacedock',
        'donation-link' => '',

        'backend-url' => '',
        'gameshort' => '',
        'update-interval' => 2147483647
    ]
];
?>

Disable the background updates for the moment, because my browser just died.

JavaScript GC sucks


<?php

/*
 * This file is part of NotifyMe.
 *
 * (c) Joseph Cohen <joseph.cohen@dinkbit.com>
 * (c) Graham Campbell <graham@mineuk.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace NotifyMeHQ\NotifyMe;

interface GatewayInterface
{
    /**
     * Send a notification.
     *
     * @param string   $message
     * @param string[] $options
     *
     * @return \NotifyMeHQ\NotifyMe\Response
     */
    public function notify($message, array $options = []);
}

<?php

/*
 * This file is part of NotifyMe.
 *
 * (c) Joseph Cohen <joseph.cohen@dinkbit.com>
 * (c) Graham Campbell <graham@mineuk.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace NotifyMeHQ\NotifyMe;

interface GatewayInterface
{
    /**
     * Send a notification.
     *
     * @param string $to
     * @param string $message
     *
     * @return \NotifyMeHQ\NotifyMe\Response
     */
    public function notify($to, $message);
}

Make the notify interface simpler

Make the notify interface simpler


Revert "Added global middleware support"


<?php

class Cache
{

	private function createCacheKey($key, $isUserValue, $userId = null) {

		$CC_CONFIG = Config::getConfig();
		$a = $CC_CONFIG["apiKey"][0];

		if ($isUserValue) {
			$cacheKey = "{$key}{$userId}{$a}";
		}
		else {
			$cacheKey = "{$key}{$a}";
		}

		return $cacheKey;
	}

	private static function getMemcached() {

	    $CC_CONFIG = Config::getConfig();

	    $memcached = new Memcached();
	    //$server is in the format "host:port"
	    foreach($CC_CONFIG['memcached']['servers'] as $server) {

	        list($host, $port) = explode(":", $server);
	        $memcached->addServer($host, $port);
	    }

	    return $memcached;
	}

	public function store($key, $value, $isUserValue, $userId = null) {

        $cache = self::getMemcached();
		$cacheKey = self::createCacheKey($key, $userId);

		return $cache->set($cacheKey, $value);
	}

	public function fetch($key, $isUserValue, $userId = null) {

	    $cache = self::getMemcached();
		$cacheKey = self::createCacheKey($key, $isUserValue, $userId);
		$value = $cache->get($cacheKey);

		$found = true;
		if ($cache->getResultCode() == Memcached::RES_NOTFOUND) {
            $found = false;
		}

		//need to return something to distinguish a cache miss from a stored "false" preference.
		return array(
		   "found" => $found,
		   "value" => $value,
		);
	}
}

<?php

class Cache
{
	private function createCacheKey($key, $isUserValue, $userId = null) {

		$CC_CONFIG = Config::getConfig();
		$a = $CC_CONFIG["apiKey"][0];

		if ($isUserValue) {
			$cacheKey = "{$key}{$userId}{$a}";
		}
		else {
			$cacheKey = "{$key}{$a}";
		}

		return $cacheKey;
	}

	private static function getMemcached() {

	    $CC_CONFIG = Config::getConfig();

	    $memcached = new Memcached();
	    //$server is in the format "host:port"
	    foreach($CC_CONFIG['memcached']['servers'] as $server) {

	        list($host, $port) = explode(":", $server);
	        $memcached->addServer($host, $port);
	    }

	    return $memcached;
	}

	public function store($key, $value, $isUserValue, $userId = null) {

		//$cacheKey = self::createCacheKey($key, $userId);
		return false; ///apc_store($cacheKey, $value);
	}

	public function fetch($key, $isUserValue, $userId = null) {

		//$cacheKey = self::createCacheKey($key, $isUserValue, $userId);
		return false; //apc_fetch($cacheKey);
	}
}

Disable the APC cache for Ubuntu 14.04. APC is deprecated now so we need a better solution anyways.


<?php
namespace Rocketeer\Strategies\Check;

use Rocketeer\Abstracts\Strategies\AbstractPolyglotStrategy;
use Rocketeer\Interfaces\Strategies\CheckStrategyInterface;

class PolyglotStrategy extends AbstractPolyglotStrategy implements CheckStrategyInterface
{
	/**
	 * Check that the PM that'll install
	 * the app's dependencies is present
	 *
	 * @return boolean
	 */
	public function manager()
	{
		$results = $this->executeStrategiesMethod('manager');

		return $this->checkStrategiesResults($results);
	}

	/**
	 * Check that the language used by the
	 * application is at the required version
	 *
	 * @return boolean
	 */
	public function language()
	{
		$results = $this->executeStrategiesMethod('language');

		return $this->checkStrategiesResults($results);
	}

	/**
	 * Check for the required extensions
	 *
	 * @return array
	 */
	public function extensions()
	{
		$missing    = [];
		$extensions = $this->executeStrategiesMethod('extensions');
		foreach ($extensions as $extension) {
			$missing = array_merge($missing, $extension);
		}

		return $missing;
	}

	/**
	 * Check for the required drivers
	 *
	 * @return array
	 */
	public function drivers()
	{
		$missing = [];
		$drivers = $this->executeStrategiesMethod('drivers');
		foreach ($drivers as $driver) {
			$missing = array_merge($missing, $driver);
		}

		return $missing;
	}
}

<?php
namespace Rocketeer\Strategies\Check;

use Rocketeer\Abstracts\Strategies\AbstractPolyglotStrategy;
use Rocketeer\Interfaces\Strategies\CheckStrategyInterface;

class PolyglotStrategy extends AbstractPolyglotStrategy implements CheckStrategyInterface
{
	/**
	 * Check that the PM that'll install
	 * the app's dependencies is present
	 *
	 * @return boolean
	 */
	public function manager()
	{
		$this->executeStrategiesMethod('manager');

		return $this->passed();
	}

	/**
	 * Check that the language used by the
	 * application is at the required version
	 *
	 * @return boolean
	 */
	public function language()
	{
		$this->executeStrategiesMethod('language');

		return $this->passed();
	}

	/**
	 * Check for the required extensions
	 *
	 * @return array
	 */
	public function extensions()
	{
		$missing    = [];
		$extensions = $this->executeStrategiesMethod('extensions');
		foreach ($extensions as $extension) {
			$missing = array_merge($missing, $extension);
		}

		return $missing;
	}

	/**
	 * Check for the required drivers
	 *
	 * @return array
	 */
	public function drivers()
	{
		$missing = [];
		$drivers = $this->executeStrategiesMethod('drivers');
		foreach ($drivers as $driver) {
			$missing = array_merge($missing, $driver);
		}

		return $missing;
	}
}

Use passed in polyglot check

Use passed in polyglot check


<?php
/**
 * This file is part of Railt package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
declare(strict_types=1);

namespace Railt\Reflection\Standard\Scalars;

use Railt\Reflection\Standard\StandardType;

/**
 * The ID standard scalar implementation.
 *
 * @see http://facebook.github.io/graphql/#sec-ID
 */
final class IDType extends StringType implements StandardType
{
    /**
     * The ID scalar public name constant.
     * This name will be used in the future as
     * the type name available for use in our GraphQL schema.
     */
    protected const SCALAR_TYPE_NAME = 'ID';

    /**
     * Short ID scalar public description.
     */
    protected const TYPE_DESCRIPTION = 'The `ID` scalar type represents a unique identifier, often used to ' .
        'refetch an object or as key for a cache. The ID type appears in a JSON ' .
        'response as a String; however, it is not intended to be human-readable. ' .
        'When expected as an input type, any string (such as `"4"`) or integer ' .
        '(such as `4`) input value will be accepted as an ID.';
}

<?php
/**
 * This file is part of Railt package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
declare(strict_types=1);

namespace Railt\Reflection\Standard\Scalars;

use Railt\Reflection\Standard\StandardType;

/**
 * The ID standard scalar implementation.
 *
 * @see http://facebook.github.io/graphql/#sec-ID
 */
final class IDType extends StringType implements StandardType
{
    /**
     * The ID scalar public name constant.
     * This name will be used in the future as
     * the type name available for use in our GraphQL schema.
     */
    protected const SCALAR_TYPE_NAME = 'ID';

    /**
     * Short ID scalar public description.
     */
    protected const TYPE_DESCRIPTION = 'The `ID` scalar type represents a unique identifier, often used to ' .
        'refetch an object or as key for a cache. The ID type appears in a JSON ' .
        'response as a String; however, it is not intended to be human-readable. ' .
        'When expected as an input type, any string (such as `"4"`) or integer ' .
        '(such as `4`) input value will be accepted as an ID.';

    /**
     * @param mixed|string $value
     * @return bool
     */
    public function isCompatible($value): bool
    {
        return \is_string($value) || \is_int($value);
    }
}

Add integer compatibility with integer

Add integer compatibility with integer


<?php

namespace Quran;

use Exception;
use ReflectionClass;

class Quran extends Base
{
    protected $fragments;

    public static function settings(array $settings)
    {
    }

    public function get(array $arguments = [])
    {
        $total = [];
        foreach ($this->fragments as $fragment) {
            $total[] = $fragment->build();
        }

        pr($this->fetchData($total));

        return $this->data;
    }

    public static function __callStatic(string $name, array $arguments)
    {
        return (new static )->__call($name, $arguments);
    }

    public function __call(string $name, array $arguments)
    {
        try {
            $className = 'Quran\\Fragments\\' . ucfirst($name);

            if (!class_exists($className)) {
                throw new Exception(
                    sprintf('"%s" is not a valid chain', $name)
                );
            }

            $fragment = (new ReflectionClass($className))->newInstanceArgs([$name, $arguments]);

            $this->fragments[spl_object_hash($fragment)] = $fragment;
        } catch (Exception $exception) {
            throw new Exception(
                $exception->getMessage(),
                $exception->getCode(),
                $exception
            );
        }

        return $this;
    }
}

<?php

namespace Quran;

use Exception;

class Quran
{
    public static function __callStatic(string $name, array $arguments)
    {
        return (new static())->__call($name, $arguments);
    }

    public function __call(string $name, array $arguments)
    {
        $classname = '\\Quran\\Rules\\' . ucfirst($name);

        if (!class_exists($classname)) {
            throw new Exception(
                sprintf("Class '%s' not found, Pleaes type valid chain.", $classname)
            );
        }

        return $this;
    }

    public function get(array $arguments)
    {
        return 'abc';
    }
}

Add Main class adopt new design pattern instead of IDSL


<?php

namespace QuickCheck;

use PHPUnit\Framework\TestCase;
use QuickCheck\Generator as Gen;
use QuickCheck\PHPUnit\PropertyConstraint;

class PHPUnitIntegrationTest extends TestCase {
    /**
     * Test example from PHPUnit integration documentation
     */
    public function testStringsAreLessThanTenChars()
    {
        $property = Property::forAll(
            [Gen::strings()],
            fn ($s): bool => 10 > strlen($s)
        );

        $this->assertFalse(
            PropertyConstraint::check(50)->evaluate(
                $property,
                'Expected property to fail',
                true
            )
        );
    }
}

<?php

namespace QuickCheck;

use PHPUnit\Framework\TestCase;
use QuickCheck\Generator as Gen;
use QuickCheck\PHPUnit\PropertyConstraint;

class PHPUnitIntegrationTest extends TestCase {
    /**
     * Test example from PHPUnit integration documentation
     */
    public function testStringsAreLessThanTenChars()
    {
        $property = Property::forAll(
            [Gen::strings()],
            function ($s) { return 10 > strlen($s); }
        );

        $this->assertFalse(
            PropertyConstraint::check(50)->evaluate(
                $property,
                'Expected property to fail',
                true
            )
        );
    }
}

Rewrite lambda to work with 7.3

Rewrite lambda to work with 7.3


<?php
namespace PhpBrew\Tasks;
use CLIFramework\Logger;
use GetOptionKit\OptionResult;

abstract class BaseTask
{
    public $logger;

    public $options;

    public $startedAt;

    public $finishedAt;

    public function __construct(Logger $logger, OptionResult $options = NULL)
    {
        $this->startedAt = microtime(true);
        $this->logger = $logger;
        if ($options) {
            $this->options = $options;
        }
    }

    public function setLogger($logger)
    {
        $this->logger = $logger;
    }

    public function getLogger()
    {
        return $this->logger;
    }

    public function info($msg)
    {
        if ($this->logger) {
            $this->logger->info($msg);
        }
    }

    public function debug($msg)
    {
        if ($this->logger) {
            $this->logger->debug($msg);
        }
    }

    public function __destruct()
    {
        $this->finishedAt = microtime(true);
        // $this->logger->debug("---> Task " . get_class($this) . " finished in " . round(($this->finishedAt - $this->startedAt) / 1000,2) . 'ms' );
    }
}

<?php
namespace PhpBrew\Tasks;
use CLIFramework\Logger;
use GetOptionKit\OptionResult;

abstract class BaseTask
{
    public $logger;

    public $options;

    public $startedAt;

    public $finishedAt;

    public function __construct(Logger $logger, OptionResult $options = NULL)
    {
        $this->startedAt = microtime(true);
        $this->logger = $logger;
        if ($options) {
            $this->options = $options;
        } else {
            $this->options = new OptionResult;
        }
    }

    public function setLogger($logger)
    {
        $this->logger = $logger;
    }

    public function getLogger()
    {
        return $this->logger;
    }

    public function info($msg)
    {
        if ($this->logger) {
            $this->logger->info($msg);
        }
    }

    public function debug($msg)
    {
        if ($this->logger) {
            $this->logger->debug($msg);
        }
    }

    public function __destruct()
    {
        $this->finishedAt = microtime(true);
        // $this->logger->debug("---> Task " . get_class($this) . " finished in " . round(($this->finishedAt - $this->startedAt) / 1000,2) . 'ms' );
    }
}

Create empty option result if option result is not set


<?php

namespace KevinVR\FootbelProcessorBundle\Command;

use PhpAmqpLib\Message\AMQPMessage;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class ResourceProcessorAllCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this->setName('resource:process:all');

    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        try {
            $queueworker = $this->getContainer()->get('rabbit_worker');
        } catch (\Exception $e) {
            // @TODO: Logging!
            exit(1);
        }

        $em = $this->getContainer()->get('doctrine')->getManager();
        $resourceRepository = $em->getRepository("FootbelBackendBundle:Resource");
        $resources = $resourceRepository->findResourcesToProcess();

        foreach ($resources as $resource) {
            $resourceFileProcessor = new ResourceFileProcessor(
                $resource,
                $queueworker,
                $em
            );
            $resourceFileProcessor->process();
        }

        exit(0);
    }
}

<?php

namespace KevinVR\FootbelProcessorBundle\Command;

use KevinVR\FootbelProcessorBundle\Processor\ResourceFileProcessor;
use PhpAmqpLib\Message\AMQPMessage;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class ResourceProcessorAllCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this->setName('resource:process:all');

    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        try {
            $queueworker = $this->getContainer()->get('rabbit_worker');
        } catch (\Exception $e) {
            $output->writeln('Cannot connect to the queue!');
            exit(1);
        }

        $em = $this->getContainer()->get('doctrine')->getManager();
        $resourceRepository = $em->getRepository("FootbelBackendBundle:Resource");
        $resources = $resourceRepository->findResourcesToProcess();

        foreach ($resources as $resource) {
            $resourceFileProcessor = new ResourceFileProcessor(
                $resource,
                $queueworker,
                $em
            );
            $resourceFileProcessor->process();
        }
        $output->writeln('All resources processed!');
        exit(0);
    }
}

Use statement + output added

Use statement + output added


<?php
namespace Oro\Bundle\OrganizationBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class BusinessUnitTreeSelectType extends AbstractType
{
    public function getParent()
    {
        return 'oro_business_unit_tree';
    }

    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(
            array(
                'configs' => array(),
                'business_unit_ids' => array(),
            )
        );
    }

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

    /**
     * {@inheritdoc}
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['business_unit_ids'] = $options['business_unit_ids'];
    }
}

<?php
namespace Oro\Bundle\OrganizationBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class BusinessUnitTreeSelectType extends AbstractType
{
    public function getParent()
    {
        return 'oro_business_unit_tree';
    }

    /**
     * {@inheritdoc}
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(
            array(
                'configs' => array(
                    'is_translated_option' => false,
                    'is_safe'              => false,
                ),
                'business_unit_ids' => array(),
            )
        );
    }

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

    /**
     * {@inheritdoc}
     */
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['business_unit_ids'] = $options['business_unit_ids'];
    }
}

BAP-2986: Fix business unit assign in user edit page
 - Refactor business unit form type


<?php

namespace ZpgRtf\Objects;

class GoogleStreetViewObject
{

}

<?php

namespace ZpgRtf\Objects;

class GoogleStreetViewObject implements \JsonSerializable
{
    /** @var CoordinatesObject */
    private $coordinates;

    /** @var float */
    private $heading;

    /** @var float */
    private $pitch;

    /**
     * @return CoordinatesObject
     */
    public function getCoordinates()
    {
        return $this->coordinates;
    }

    /**
     * @param CoordinatesObject $coordinates
     *
     * @return GoogleStreetViewObject
     */
    public function setCoordinates(CoordinatesObject $coordinates)
    {
        $this->coordinates = $coordinates;

        return $this;
    }

    /**
     * @return float
     */
    public function getHeading()
    {
        return $this->heading;
    }

    /**
     * @param float $heading
     *
     * @return GoogleStreetViewObject
     */
    public function setHeading($heading)
    {
        $this->heading = $heading;

        return $this;
    }

    /**
     * @return float
     */
    public function getPitch()
    {
        return $this->pitch;
    }

    /**
     * @param float $pitch
     *
     * @return GoogleStreetViewObject
     */
    public function setPitch($pitch)
    {
        $this->pitch = $pitch;

        return $this;
    }

    /** {@inheritDoc} */
    public function jsonSerialize() {
        return [
            'coordinates' => $this->getCoordinates(),
            'heading' => $this->getHeading(),
            'pitch' => $this->getPitch(),
        ];
    }
}

Add google street view object

Add google street view object


<?php

namespace Predis;

use Predis\Network\IConnection;
use Predis\Network\IConnectionCluster;
use Predis\Network\ConnectionCluster;

class Utils {
    public static function isCluster(IConnection $connection) {
        return $connection instanceof IConnectionCluster;
    }

    public static function onCommunicationException(CommunicationException $exception) {
        if ($exception->shouldResetConnection()) {
            $connection = $exception->getConnection();
            if ($connection->isConnected()) {
                $connection->disconnect();
            }
        }
        throw $exception;
    }

    public static function filterArrayArguments(Array $arguments) {
        if (count($arguments) === 1 && is_array($arguments[0])) {
            return $arguments[0];
        }
        return $arguments;
    }
}

<?php

namespace Predis;

use Predis\Network\IConnection;
use Predis\Network\IConnectionCluster;

class Utils {
    public static function isCluster(IConnection $connection) {
        return $connection instanceof IConnectionCluster;
    }

    public static function onCommunicationException(CommunicationException $exception) {
        if ($exception->shouldResetConnection()) {
            $connection = $exception->getConnection();
            if ($connection->isConnected()) {
                $connection->disconnect();
            }
        }
        throw $exception;
    }

    public static function filterArrayArguments(Array $arguments) {
        if (count($arguments) === 1 && is_array($arguments[0])) {
            return $arguments[0];
        }
        return $arguments;
    }
}

Remove a useless 'use' directive.

Remove a useless 'use' directive.


<?php
if ( ! function_exists( 'on_cache_please' ) ){
	/**
	 * Function to storage the cache on automatic.
	 * @since 1.0.0
	 * @param
	 */
	function on_cache_please( array $args = array() ) {
		$args = is_array( $args ) ? $args : array();
		$args = wp_parse_args( $args, array(
			'name' => '',
			'callback' => false,
			'duration' => HOUR_IN_SECONDS,
		));

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

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

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

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

Update file based on the php:lint task

Update file based on the php:lint task


<article id="post-<?php the_ID(); ?>" <?php post_class('index-card'); ?>>

<a href="<?php echo esc_attr( get_field('article_url', get_the_ID()) ); ?>"><?php the_title(); ?>

            Published by <?php echo get_the_publisher_link(get_the_ID()) ?>
            <time class="updated" datetime="<?php echo get_the_time('c') ?>" pubdate><?php echo get_the_time('F jS, Y') ?></time>

<?php echo get_the_publisher_logo( get_the_ID() ); ?>

<?php the_content(); ?>

<?php  echo get_the_term_list(get_the_ID(),'in-the-media-tags', 'tagged as: ', ', ') ?>

        <?php edit_post_link('Edit this \'In the Media\' Item','','

'); ?>

<article id="post-<?php the_ID(); ?>" <?php post_class('index-card'); ?>>

<a href="<?php echo esc_attr( get_field('in_the_media_url', get_the_ID()) ); ?>"><?php the_title(); ?>

            Published by <?php echo get_the_publisher_link(get_the_ID()) ?>
            <time class="updated" datetime="<?php echo get_the_time('c') ?>" pubdate><?php echo get_the_time('F jS, Y') ?></time>

<?php echo get_the_publisher_logo( get_the_ID() ); ?>

<?php the_content(); ?>

<?php  echo get_the_term_list(get_the_ID(),'in-the-media-tags', 'tagged as: ', ', ') ?>

        <?php edit_post_link('Edit this \'In the Media\' Item','','

'); ?>

Fix 'In the Media' title

Fix 'In the Media' title


<?php

final class DifferentialQueryDiffsConduitAPIMethod
  extends DifferentialConduitAPIMethod {

  public function getAPIMethodName() {
    return 'differential.querydiffs';
  }

  public function getMethodDescription() {
    return pht('Query differential diffs which match certain criteria.');
  }

  protected function defineParamTypes() {
    return array(
      'ids' => 'optional list<uint>',
      'revisionIDs' => 'optional list<uint>',
    );
  }

  protected function defineReturnType() {
    return 'list<dict>';
  }

  protected function execute(ConduitAPIRequest $request) {
    $ids = $request->getValue('ids', array());
    $revision_ids = $request->getValue('revisionIDs', array());

    $diffs = array();
    if ($ids || $revision_ids) {
      $diffs = id(new DifferentialDiffQuery())
        ->setViewer($request->getUser())
        ->withIDs($ids)
        ->withRevisionIDs($revision_ids)
        ->needChangesets(true)
        ->execute();
    }

    return mpull($diffs, 'getDiffDict', 'getID');
  }

}

<?php

final class DifferentialQueryDiffsConduitAPIMethod
  extends DifferentialConduitAPIMethod {

  public function getAPIMethodName() {
    return 'differential.querydiffs';
  }

  public function getMethodDescription() {
    return pht('Query differential diffs which match certain criteria.');
  }

  protected function defineParamTypes() {
    return array(
      'ids' => 'optional list<uint>',
      'revisionIDs' => 'optional list<uint>',
    );
  }

  protected function defineReturnType() {
    return 'list<dict>';
  }

  protected function execute(ConduitAPIRequest $request) {
    $ids = $request->getValue('ids', array());
    $revision_ids = $request->getValue('revisionIDs', array());

    if (!$ids && !$revision_ids) {
      // This method just returns nothing if you pass no constraints because
      // pagination hadn't been invented yet in 2008 when this method was
      // written.
      return array();
    }

    $query = id(new DifferentialDiffQuery())
      ->setViewer($request->getUser())
      ->needChangesets(true);

    if ($ids) {
      $query->withIDs($ids);
    }

    if ($revision_ids) {
      $query->withRevisionIDs($revision_ids);
    }

    $diffs = $query->execute();

    return mpull($diffs, 'getDiffDict', 'getID');
  }

}

Make differential.querydiffs more liberal about arguments

Summary:
Fixes T12092. D17164 made `DiffQuery` more strict about arguments using modern conventions, but `differential.querydiffs` uses bizarre ancient conventions.

Give it more modern conventions instead.

Test Plan: Made a `querydiffs` call with only revision IDs.

Reviewers: chad

Reviewed By: chad

Maniphest Tasks: T12092

Differential Revision: https://secure.phabricator.com/D17172


Add minimum versions to required dependencies. Add PEAR2_Console_CommandLine as a required dep.

git-svn-id: 71b65f7ff3646a85e1ba76c778efde6466075005@299668 c90b9560-bf6c-de11-be94-00142212c4b1


<?php

namespace FireDIY\PrivateMessageBundle\Validator;

use FireDIY\PrivateMessageBundle\Entity\Conversation;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

/**
 * Class ConversationValidator
 * @package FireDIY\PrivateMessageBundle\Validator
 */
class ConversationValidator
{
    const RECIPIENT_VIOLATION = 'You cannot send a message to yourself';

    /**
     * Entry point of the conversation's validation process.
     *
     * @param Conversation              $conversation : instance of the conversation to validate.
     * @param ExecutionContextInterface $context      : instance of the execution context.
     */
    public static function validate(Conversation $conversation, ExecutionContextInterface $context)
    {
        self::validateRecipients($conversation, $context);
    }

    /**
     * Make sure the author of the conversation is not sending a message to himself.
     *
     * @param Conversation              $conversation : instance of the conversation to validate.
     * @param ExecutionContextInterface $context      : instance of the execution context.
     */
    private static function validateRecipients(Conversation $conversation, ExecutionContextInterface $context)
    {
        if (in_array($conversation->getAuthor(), $conversation->getRecipients())) {
            $context
                ->buildViolation(self::RECIPIENT_VIOLATION)
                ->atPath('recipients')
                ->addViolation();
        }
    }
}

<?php

namespace FireDIY\PrivateMessageBundle\Validator;

use FireDIY\PrivateMessageBundle\Entity\Conversation;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

/**
 * Class ConversationValidator
 * @package FireDIY\PrivateMessageBundle\Validator
 */
class ConversationValidator
{
    const RECIPIENT_VIOLATION = 'You cannot send a message to yourself';

    /**
     * Entry point of the conversation's validation process.
     *
     * @param Conversation              $conversation : instance of the conversation to validate.
     * @param ExecutionContextInterface $context      : instance of the execution context.
     */
    public static function validate(Conversation $conversation, ExecutionContextInterface $context)
    {
        self::validateRecipients($conversation, $context);
    }

    /**
     * Make sure the author of the conversation is not sending a message to himself.
     *
     * @param Conversation              $conversation : instance of the conversation to validate.
     * @param ExecutionContextInterface $context      : instance of the execution context.
     */
    private static function validateRecipients(Conversation $conversation, ExecutionContextInterface $context)
    {
        // This could be NULL or array.
        $recipients = $conversation->getRecipients();

        if (is_array($recipients) && in_array($conversation->getAuthor(), $recipients)) {
            $context
                ->buildViolation(self::RECIPIENT_VIOLATION)
                ->atPath('recipients')
                ->addViolation();
        }
    }
}

Fix PHP warning when submitting new conversation without any recipient


<?php
/**
 * CakeCMS Core
 *
 * This file is part of the of the simple cms based on CakePHP 3.
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @package   Core
 * @license   MIT
 * @copyright MIT License http://www.opensource.org/licenses/mit-license.php
 * @link      https://github.com/CakeCMS/Core".
 * @author    Sergey Kalistratov <kalistratov.s.m@gmail.com>
 */

namespace Test\App\Html;

/**
 * Class HtmlApplication
 *
 * @package Test\App\Html
 */
class HtmlApplication
{

    /**
     * @return string
     */
    public function getFunctionName()
    {
        return __FUNCTION__;
    }
}

<?php
/**
 * CakeCMS Core
 *
 * This file is part of the of the simple cms based on CakePHP 3.
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @package   Core
 * @license   MIT
 * @copyright MIT License http://www.opensource.org/licenses/mit-license.php
 * @link      https://github.com/CakeCMS/Core".
 * @author    Sergey Kalistratov <kalistratov.s.m@gmail.com>
 */

namespace Test\App\Html;

/**
 * Class HtmlApplication
 *
 * @package Test\App\Html
 */
class HtmlApplication
{

    /**
     * @return string
     */
    public static function getFunctionName()
    {
        return __FUNCTION__;
    }
}

Set static method for test

Set static method for test


<?php

namespace Hoard\Test\Bucket;
use Hoard\Test\TestCase;
use Model\Bucket;

class CreateTest extends TestCase
{

    public function testCreateBucket()
    {

        $bucket_data = array(
            '_id' => 'test-bucket',
            'name' => 'Test Bucket'
        );
        $bucket = new Bucket($bucket_data);
        $this->assertFalse(Bucket::exists($bucket->id));
        $bucket->save();
        $this->assertTrue(Bucket::exists($bucket->id));

    }

}

<?php

namespace Hoard\Test\Bucket;
use Hoard\Test\TestCase;
use Model\Bucket;

class CreateTest extends TestCase
{

    /**
     * Test that the model abstraction is working
     */
    public function testCreateBucket()
    {

        $bucket_data = array(
            '_id' => 'test-bucket',
            'description' => 'Test Bucket',
        );
        $bucket = new Bucket($bucket_data);
        $this->assertFalse(Bucket::exists($bucket->id));
        $bucket->save();
        $this->assertTrue(Bucket::exists($bucket->id));

    }

    /**
     * Make sure the data is actually stored in the databse
     */
    public function testCreateBucketDataStored()
    {
        $bucket_data = array(
            '_id' => 'test-bucket',
            'description' => 'Test Bucket',
        );
        $collection = $this->mongo->selectCollection(Bucket::$collection);
        $this->assertEquals(0, $collection->count());
        $bucket = new Bucket($bucket_data);
        $bucket->save();
        $this->assertEquals(1, $collection->count());
        $this->assertEquals(
            array('description' => 'Test Bucket'),
            $collection->findOne(array(), array('_id' => 0, 'description' => 1))
        );
    }

}

Make sure created buckets are stored in database correctly


<?php

use Codeception\Configuration;
use Codeception\Util\Debug;
use Illuminate\Filesystem\Filesystem;

/**
 * Output Path
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 */
trait OutputPath
{
    /**
     * Creates an output path, if it does not already exist
     */
    public function createOutputPath()
    {
        if(!file_exists($this->outputPath())){
            mkdir($this->outputPath(), 0755, true);

            Debug::debug(sprintf('<info>Created output path </info><debug>%s</debug>', $this->outputPath()));
        }
    }

    /**
     * Deletes all files and folders inside the given path
     *
     * @param string $path
     */
    public function emptyPath($path)
    {
        // Remove all created folders inside output path
        $fs = new Filesystem();
        $folders = $fs->directories($path);

        foreach($folders as $directory){
            $fs->deleteDirectory($directory);
        }
    }

    /**
     * Returns the output directory path
     *
     * @return string
     * @throws \Codeception\Exception\ConfigurationException
     */
    public function outputPath()
    {
        return Configuration::outputDir();
    }
}

<?php

use Codeception\Configuration;
use Codeception\Util\Debug;
use Illuminate\Filesystem\Filesystem;

/**
 * Output Path
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 */
trait OutputPath
{
    /**
     * Creates an output path, if it does not already exist
     */
    public function createOutputPath()
    {
        if(!file_exists($this->outputPath())){
            mkdir($this->outputPath(), 0755, true);

            Debug::debug(sprintf('<info>Created output path </info><debug>%s</debug>', $this->outputPath()));
        }
    }

    /**
     * Deletes all files and folders inside the given path
     *
     * @param string $path
     */
    public function emptyPath($path)
    {
        // Remove all created folders inside output path
        $fs = new Filesystem();
        $fs->cleanDirectory($path);

        // Not all files might have been removed by
        // the delete directory method. Therefore, we
        // search the dir for files and remove those as well.
        $files = $fs->files($path);
        $fs->delete($files);
    }

    /**
     * Returns the output directory path
     *
     * @return string
     * @throws \Codeception\Exception\ConfigurationException
     */
    public function outputPath()
    {
        return Configuration::outputDir();
    }
}

Fix empty Path not removing files correctly


<?php
/* (c) Stephan Wentz <stephan@wentz.it>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Deployer;

use Deployer\Utility\Httpie;

set('hipchat_color', 'green');
set('hipchat_from', '{{target}}');
set('hipchat_message', '_{{user}}_ deploying `{{branch}}` to *{{target}}*');

desc('Notifying Hipchat channel of deployment');
task('hipchat:notify', function () {
    $params = [
        'room_id' => get('hipchat_room_id'),
        'from' => get('target'),
        'message' => get('hipchat_message'),
        'color' => get('hipchat_color'),
        'auth_token' => get('hipchat_token'),
        'notify' => 0,
        'format' => 'json',
    ];

    Httpie::get('https://api.hipchat.com/v1/rooms/message')
        ->query($params)
        ->send();
});

<?php
/* (c) Stephan Wentz <stephan@wentz.it>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Deployer;

use Deployer\Utility\Httpie;

set('hipchat_color', 'green');
set('hipchat_from', '{{target}}');
set('hipchat_message', '_{{user}}_ deploying `{{branch}}` to *{{target}}*');
set('hipchat_url', 'https://api.hipchat.com/v1/rooms/message');

desc('Notifying Hipchat channel of deployment');
task('hipchat:notify', function () {
    $params = [
        'room_id' => get('hipchat_room_id'),
        'from' => get('target'),
        'message' => get('hipchat_message'),
        'color' => get('hipchat_color'),
        'auth_token' => get('hipchat_token'),
        'notify' => 0,
        'format' => 'json',
    ];

    Httpie::get(get('hipchat_url'))
        ->query($params)
        ->send();
});

Allow changing the server URL

Allow changing the server URL

Allow setting the URL if you are using a self hosted hipchat instance


<?php
	namespace Bolt\Api\Request;

	use Bolt\Base;
	use Bolt\Arrays;

	class InputMask extends Base
	{
		public $name;
		public $type;
		public $children = array();
		public $options = array();

		public function __construct($data = null)
		{
			parent::__construct($data);
		}

		public function add($name, $type = null, $options = array())
		{
			$structure = array(
				"name" => $name,
				"type" => $type,
				"options" => $options
			);

			$class = ($type !== null) ? $type : InputMask::class;

			$this->children[] = new $class($structure);

			return $this;
		}

		public function inflate($fields)
		{
			foreach ($fields as $key => $value)
			{
				if (Arrays::type($fields) === "numeric" || is_integer($key))
				{
					$this->add($value, null, ["required" => true]);
				}
				else
				{
					$mask = new InputMask();
					$mask->name($key);
					$mask->inflate($value);
					$mask->options(["required" => true]);
					$this->children[] = $mask;
				}
			}

			return $this;
		}
	}
?>

<?php
	namespace Bolt\Api\Request;

	use Bolt\Base;
	use Bolt\Arrays;

	class InputMask extends Base
	{
		public $name;
		public $type;
		public $children = array();
		public $options = array();

		public function __construct($data = null)
		{
			parent::__construct($data);
		}

		public function add($name, $type = null, $options = array())
		{
			$structure = array(
				"name" => $name,
				"type" => $type,
				"options" => $options
			);

			$class = ($type !== null) ? $type : InputMask::class;

			$this->children[] = new $class($structure);

			return $this;
		}

		public function inflate($fields)
		{
			foreach ($fields as $key => $value)
			{
				if (Arrays::type($fields) === "numeric" || is_integer($key))
				{
					$this->add($value, null, ["required" => true]);
				}
				else
				{
					$mask = new InputMask();
					$mask->name($key);
					$mask->inflate($value);
					$mask->options(["required" => true]);
					$this->children[] = $mask;
				}
			}

			return $this;
		}

		public function options($data = null)
		{
			if ($data === null)
			{
				return $this->options;
			}

			$this->options = array_merge($this->options, $data);

			return $this;
		}
	}
?>

Update options method to merge new data

Update options method to merge new data


<?php

class CRM_Mosaico_Page_EditorIframe extends CRM_Mosaico_Page_Editor {

}

<?php

class CRM_Mosaico_Page_EditorIframe extends CRM_Mosaico_Page_Editor {

  /**
   * Modify return value of parent:: method.
   */
  protected function getScriptUrls() {
    $scriptUrls = parent::getScriptUrls();

    CRM_Utils_Hook::singleton()->invoke(['scriptUrls'], $scriptUrls, $null, $null,
      $null, $null, $null,
      'civicrm_mosaicoScriptUrlsAlter'
    );
    return $scriptUrls;
  }

  /**
   * Modify return value of parent:: method.
   */
  protected function getStyleUrls() {
    $styleUrls = parent::getStyleUrls();

    CRM_Utils_Hook::singleton()->invoke(['styleUrls'], $styleUrls, $null, $null,
      $null, $null, $null,
      'civicrm_mosaicoStyleUrlsAlter'
    );
    return $styleUrls;
  }
}

Add hooks to alter relevant assets in the Mosaico interface


<?php

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

namespace Sylius\Component\Cart\Context;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
class CartNotFoundException extends \RuntimeException
{
    /**
     * {@inheritdoc}
     */
    public function __construct(\Exception $previousException = null)
    {
        parent::__construct('Sylius was not able to figure out the current cart.', 0, $previousException);
    }
}

<?php

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

namespace Sylius\Component\Cart\Context;

/**
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 */
class CartNotFoundException extends \RuntimeException
{
    /**
     * {@inheritdoc}
     */
    public function __construct($message = null, \Exception $previousException = null)
    {
        parent::__construct($message ?: 'Sylius was not able to figure out the current cart.', 0, $previousException);
    }
}

Rework the cart not found exception

[Cart] Rework the cart not found exception


<?php
/**
 * Plugin Name: Culture Object
 * Plugin URI: http://cultureobject.co.uk
 * Description: A framework as a plugin to enable sync of culture objects into WordPress.
 * Version: 3.0.0-beta.1
 * Author: Liam Gladdy / Thirty8 Digital
 * Text Domain: culture-object
 * Author URI: https://github.com/lgladdy
 * GitHub Plugin URI: Thirty8Digital/CultureObject
 * GitHub Branch: dev
 * License: Apache 2 License
 */

require_once('CultureObject/CultureObject.class.php');
$cos = new \CultureObject\CultureObject();

/* General Functions. These need to go into their own file one day. */

function cos_get_remapped_field_name($field_key) {
    global $cos;
    return $cos->helper->cos_get_remapped_field_name($field_key);
}

function cos_remapped_field_name($field_key) {
    global $cos;
    return $cos->helper->cos_remapped_field_name($field_key);
}

function cos_get_field($field_key) {
    $id = get_the_ID();
    if (!$id) return false;
    return get_post_meta($id, $field_key, true);
}

function cos_the_field($field_key) {
    echo cos_get_field($field_key);
}

<?php
/**
 * Plugin Name: Culture Object
 * Plugin URI: http://cultureobject.co.uk
 * Description: A framework as a plugin to enable sync of culture objects into WordPress.
 * Version: 3.0.0-beta.1
 * Author: Liam Gladdy / Thirty8 Digital
 * Text Domain: culture-object
 * Author URI: https://github.com/lgladdy
 * GitHub Plugin URI: Thirty8Digital/CultureObject
 * GitHub Branch: master
 * License: Apache 2 License
 */

require_once('CultureObject/CultureObject.class.php');
$cos = new \CultureObject\CultureObject();

/* General Functions. These need to go into their own file one day. */

function cos_get_remapped_field_name($field_key) {
    global $cos;
    return $cos->helper->cos_get_remapped_field_name($field_key);
}

function cos_remapped_field_name($field_key) {
    global $cos;
    return $cos->helper->cos_remapped_field_name($field_key);
}

function cos_get_field($field_key) {
    $id = get_the_ID();
    if (!$id) return false;
    return get_post_meta($id, $field_key, true);
}

function cos_the_field($field_key) {
    echo cos_get_field($field_key);
}

Update branch for git updater

Update branch for git updater


<?php
namespace AppBundle\Game;

/**
 * A square the contains X or O values.
 *
 * @author Brian Feaver <brian.feaver@gmail.com>
 */
class XoSquare implements Square
{
    /**
     * @var string
     */
    private $value;

    function __construct($value = null)
    {
        $this->value = $value;
    }

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

    /**
     * @param mixed $value
     */
    public function setValue($value)
    {
        if ($value !== 'X' && $value !== 'O' && !is_null($value)) {
            throw new \RuntimeException(sprintf('Value must be X or O, value %s given.', $value));
        }
        $this->value = $value;
    }
}

<?php
namespace AppBundle\Game;

/**
 * A square the contains X or O values.
 *
 * @author Brian Feaver <brian.feaver@gmail.com>
 */
class XoSquare implements Square
{
    /**
     * @var string
     */
    private $value;

    function __construct($value = null)
    {
        $this->value = $value;
    }

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

    /**
     * @param mixed $value
     */
    public function setValue($value)
    {
        if ($value !== 'X' && $value !== 'O' && !is_null($value)) {
            throw new \InvalidArgumentException(sprintf('Value must be X or O, value %s given.', $value));
        }
        $this->value = $value;
    }
}

Change invalid value to InvalidArgException


<?php

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

namespace Symfony\Bundle\TwigBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Bundle\TwigBundle\DependencyInjection\Compiler\TwigEnvironmentPass;

/**
 * Bundle.
 *
 * @author Fabien Potencier <fabien.potencier@symfony-project.com>
 */
class TwigBundle extends Bundle
{
    public function registerExtensions(ContainerBuilder $container)
    {
        parent::registerExtensions($container);

        $container->addCompilerPass(new TwigEnvironmentPass());
    }

    /**
     * {@inheritdoc}
     */
    public function getNamespace()
    {
        return __NAMESPACE__;
    }

    /**
     * {@inheritdoc}
     */
    public function getPath()
    {
        return strtr(__DIR__, '\\', '/');
    }
}

<?php

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

namespace Symfony\Bundle\TwigBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Bundle\TwigBundle\DependencyInjection\Compiler\TwigEnvironmentPass;

/**
 * Bundle.
 *
 * @author Fabien Potencier <fabien.potencier@symfony-project.com>
 */
class TwigBundle extends Bundle
{
    public function registerExtensions(ContainerBuilder $container)
    {
        parent::registerExtensions($container);

        $container->addCompilerPass(new TwigEnvironmentPass());
    }

    /**
     * {@inheritdoc}
     */
    public function getNamespace()
    {
        return __NAMESPACE__;
    }

    /**
     * {@inheritdoc}
     */
    protected function getPath()
    {
        return __DIR__;
    }
}

[Bundle] Make getPath() less error prone by allowing both backward and forward slashes


<?php

namespace TomPHP\ContainerConfigurator;

use TomPHP\ContainerConfigurator\Exception\UnknownContainerException;

final class ContainerAdapterFactory
{
    /**
     * @var array
     */
    private $config;

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

    /**
     * @param object $container
     *
     * @throws UnknownContainerException
     *
     * @return void
     */
    public function create($container)
    {
        $class = '';

        foreach ($this->config as $containerClass => $configuratorClass) {
            if (is_a($container, $containerClass)) {
                $class = $configuratorClass;
                break;
            }
        }

        if (!$class) {
            throw UnknownContainerException::fromContainerName(
                get_class($container),
                array_keys($this->config)
            );
        }

        $instance = new $class();
        $instance->setContainer($container);

        return $instance;
    }
}

<?php

namespace TomPHP\ContainerConfigurator;

use TomPHP\ContainerConfigurator\Exception\UnknownContainerException;

final class ContainerAdapterFactory
{
    /**
     * @var array
     */
    private $config;

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

    /**
     * @param object $container
     *
     * @throws UnknownContainerException
     *
     * @return ContainerAdapter
     */
    public function create($container)
    {
        $class = '';

        foreach ($this->config as $containerClass => $configuratorClass) {
            if (is_a($container, $containerClass)) {
                $class = $configuratorClass;
                break;
            }
        }

        if (!$class) {
            throw UnknownContainerException::fromContainerName(
                get_class($container),
                array_keys($this->config)
            );
        }

        $instance = new $class();
        $instance->setContainer($container);

        return $instance;
    }
}

Update return type in docblock

Fix: Update return type in docblock


<?php

namespace MssPhp\Schema\Response;

use JMS\Serializer\Annotation\Type;

class Picture {
    /**
     * @Type("string")
     */
    public $url;

    /**
     * @Type("integer")
     */
    public $time;

    /**
     * @Type("string")
     */
    public $title;
}

<?php

namespace MssPhp\Schema\Response;

use JMS\Serializer\Annotation\AccessType;
use JMS\Serializer\Annotation\Type;

class Picture {
    /**
     * @AccessType("public_method")
     * @Type("string")
     */
    public $url;

    public function getUrl()
    {
        return $this->url;
    }

    public function setUrl($url)
    {
        $this->url = str_replace('http://www.easymailing.eu', 'https://www.bookingsuedtirol.com', $url);
    }

    /**
     * @Type("integer")
     */
    public $time;

    /**
     * @Type("string")
     */
    public $title;
}

Replace easymailing domain with booking southtyrol


<?php
/* ------------------------------------------------------------------------ *\
 * Rewrite Rules
\* ------------------------------------------------------------------------ */

/**
 * Add various rewrite rules
 *
 * @return void
 */
function __gulp_init_namespace___rewrite_rules(): void {
    /**
     * Point to manifest generator at /manifest.json
     */
    add_rewrite_endpoint("manifest", EP_NONE);
    add_rewrite_rule("manifest\.json$", "index.php?manifest=true", "top");

    /**
     * Load offline template at /offline/
     */
    add_rewrite_endpoint("offline", EP_NONE);
    add_rewrite_rule("offline/?$", "index.php?offline=true", "top");

    /**
     * Rewrite requests to /media/ to /wp-content/themes/__gulp_init_npm_name__/assets/media/
     * to ensure no 404s occur when critical CSS is included
     */
    add_rewrite_rule("media/(.*)$", str_replace(ABSPATH, "", get_stylesheet_directory()) . "/assets/media/$1", "top");
}
add_action("init", "__gulp_init_namespace___rewrite_rules");

<?php
/* ------------------------------------------------------------------------ *\
 * Rewrite Rules
\* ------------------------------------------------------------------------ */

/**
 * Add various rewrite rules
 *
 * @return void
 */
function __gulp_init_namespace___rewrite_rules(): void {
    /**
     * Point to manifest generator at /manifest.json
     */
    add_rewrite_endpoint("manifest", EP_NONE);
    add_rewrite_rule("manifest\.json$", "index.php?manifest=true", "top");

    /**
     * Load offline template at /offline/
     */
    add_rewrite_endpoint("offline", EP_NONE);
    add_rewrite_rule("offline/?$", "index.php?offline=true", "top");

    /**
     * Rewrite requests to /media/ to /wp-content/themes/__gulp_init_npm_name__/assets/media/
     * to ensure no 404s occur when critical CSS is included
     */
    add_rewrite_rule("media/(.*)$", str_replace(ABSPATH, "", get_stylesheet_directory()) . '/assets/media/$matches[1]', "top");
}
add_action("init", "__gulp_init_namespace___rewrite_rules");

Fix root media rewrite rule

Fix root media rewrite rule


<?php

namespace Oro\Bundle\ActivityBundle\Tools;

class ActivityExtendEntityGeneratorExtension
{

}

<?php

namespace Oro\Bundle\ActivityBundle\Tools;

use CG\Generator\PhpClass;

use Oro\Bundle\EntityConfigBundle\Config\Id\FieldConfigId;
use Oro\Bundle\EntityExtendBundle\Tools\ClassBuilder;
use Oro\Bundle\EntityExtendBundle\Tools\ExtendEntityGenerator;
use Oro\Bundle\EntityExtendBundle\Tools\ExtendEntityGeneratorExtension;

class ActivityExtendEntityGeneratorExtension extends ExtendEntityGeneratorExtension
{
    /**
     * {@inheritdoc}
     */
    public function supports($actionType, array $schemas)
    {
        return ExtendEntityGenerator::ACTION_GENERATE == $actionType && !empty($schemas['relation']);
    }

    /**
     * @param array    $schema
     * @param PhpClass $class
     *
     * @return void
     */
    public function generate(array $schema, PhpClass $class)
    {
        $classBuilder = new ClassBuilder();

        $relationData = empty($schema['relationData']) ? [] : $schema['relationData'];

        $relationNames     = [];
        $supportedEntities = [];

        foreach ($relationData as $relationItem) {
            /** @var FieldConfigId $fieldConfigId */
            $fieldConfigId = $relationItem['field_id'];

            $fieldName                 = $fieldConfigId->getFieldName();
            $targetClassName           = $relationItem['target_entity'];
            $relationNames[$fieldName] = $targetClassName;
            $supportedEntities[]       = sprintf("'%s'", $targetClassName);
        }

        $getMethodBody = $addMethodBody = [
            '$className = \Doctrine\Common\Util\ClassUtils::getClass($target);',
            'if (!in_array($className, [' . implode(', ', $supportedEntities) . '])) {',
            '    throw new \RuntimeException(',
                    'sprintf(\'The association with "%s" entity was not configured.\', $className)',
                 ');',
            '}',
        ];

        foreach ($relationNames as $fieldName => $targetClassName) {
            $getMethodBody[] = sprintf(
                'if ($className == \'%s\') { return $this->%s; }',
                $targetClassName,
                $fieldName
            );

            $addMethodBody[] = sprintf(
                'if ($className == \'%s\') { $this->%s[] = %s; }',
                $targetClassName,
                $fieldName,
                '$target'
            );
        }

        $getMethodDocblock = "/**\n"
            . " * Gets the entity this note is associated with\n"
            . " *\n"
            . " * @return object|null Any configurable entity\n"
            . " */";
        $addMethodDocblock = "/**\n"
            . " * Add associated entity\n"
            . " *\n"
            . " * @param object \$target Any configurable entity that can be used with associations\n"
            . " */";

        $class
            ->setMethod(
                $classBuilder
                    ->generateClassMethod('getTargets', implode("\n", $getMethodBody))
                    ->setDocblock($getMethodDocblock)
            )
            ->setMethod(
                $classBuilder
                    ->generateClassMethod('addTarget', implode("\n", $addMethodBody), ['target'])
                    ->setDocblock($addMethodDocblock)
            );
    }
}

BAP-4209: Add EntityExtendBundle generator extension to generate activity association entities
- generator extension


#!/usr/bin/env php
<?php
chdir(__DIR__);

$returnStatus = null;
passthru('composer install --dev', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

require 'vendor/autoload.php';

passthru('./vendor/bin/phpcs --standard=' . __DIR__ . '/DWS --extensions=php -n tests DWS *.php', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration);
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
    exit(1);
}

$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
    file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
    exit(1);
}

echo "Code coverage was 100%\n";

#!/usr/bin/env php
<?php
chdir(__DIR__);

$returnStatus = null;
passthru('composer install', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

require 'vendor/autoload.php';

passthru('./vendor/bin/phpcs --standard=' . __DIR__ . '/DWS --extensions=php -n tests DWS *.php', $returnStatus);
if ($returnStatus !== 0) {
    exit(1);
}

$phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml');
$phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration);
$testRunner = new PHPUnit_TextUI_TestRunner();
$result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments);
if (!$result->wasSuccessful()) {
    exit(1);
}

$coverageFactory = new PHP_CodeCoverage_Report_Factory();
$coverageReport = $coverageFactory->create($result->getCodeCoverage());
if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) {
    file_put_contents('php://stderr', "Code coverage was NOT 100%\n");
    exit(1);
}

echo "Code coverage was 100%\n";

Remove --dev from composer install.

Remove --dev from composer install.

--dev is the default.


<?php

require_once 'AbstractBackendTest.php';

use iFixit\Matryoshka;

class MemcachedTest extends AbstractBackendTest {
   protected function setUp() {
      if (!Matryoshka\Memcached::isAvailable()) {
         $this->markTestSkipped('Backend not available!');
      }

      return parent::setUp();
   }

   protected function getBackend() {
      $memcached = new Memcached();
      $memcached->addServer('localhost', 11211);
      $memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
      $memcached->setOption(Memcached::OPT_TCP_NODELAY, true);

      return Matryoshka\Memcached::create($memcached);
   }

   public function testMemcached() {
      $backend = $this->getBackend();
      list($key, $value) = $this->getRandomKeyValue();
      $this->assertTrue($backend->set($key, $value, 1));
      // Wait for it to expire.
      sleep(2);

      $this->assertNull($backend->get($key));
   }
}

<?php

require_once 'AbstractBackendTest.php';

use iFixit\Matryoshka;

class MemcachedTest extends AbstractBackendTest {
   protected function setUp() {
      if (!Matryoshka\Memcached::isAvailable()) {
         $this->markTestSkipped('Backend not available!');
      }

      return parent::setUp();
   }

   protected function getBackend() {
      $memcached = new Memcached();
      $memcached->addServer('localhost', 11211);
      $memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);
      $memcached->setOption(Memcached::OPT_TCP_NODELAY, true);

      return Matryoshka\Memcached::create($memcached);
   }

   public function testExpiration() {
      $backend = $this->getBackend();
      list($key, $value) = $this->getRandomKeyValue();
      $this->assertTrue($backend->set($key, $value, 1));
      // Wait for it to expire.
      sleep(2);

      $this->assertNull($backend->get($key));
   }
}

Rename the Memcached test to be more accurate

Apparently, Memcached is the only Backend that implements expirations,
so it tests Expirations seperately (and not very well!) outside of
`AbstractBackendTest`. More more accurate in naming this.


<?php

namespace Bundle\MarkdownBundle\Twig\Extension;

use Bundle\MarkdownBundle\Helper\MarkdownHelper;

class MarkdownTwigExtension extends \Twig_Extension
{
    protected $helper;

    function __construct(MarkdownHelper $helper)
    {
        $this->helper = $helper;
    }

    public function getFilters()
    {
        return array(
            'markdown' => new \Twig_Filter_Method($this, 'markdown', array('is_escaper' => true)),
        );
    }

    public function markdown($txt)
    {
        return $this->helper->transform($txt);
    }

    public function getName()
    {
        return 'markdown';
    }
}

<?php

namespace Bundle\MarkdownBundle\Twig\Extension;

use Bundle\MarkdownBundle\Helper\MarkdownHelper;

class MarkdownTwigExtension extends \Twig_Extension
{
    protected $helper;

    function __construct(MarkdownHelper $helper)
    {
        $this->helper = $helper;
    }

    public function getFilters()
    {
        return array(
            'markdown' => new \Twig_Filter_Method($this, 'markdown', array('is_safe' => array('html'))),
        );
    }

    public function markdown($txt)
    {
        return $this->helper->transform($txt);
    }

    public function getName()
    {
        return 'markdown';
    }
}

Update to work with the last version of twig


<?php

namespace App\Contracts;

use App\Entities\Base\User;

/**
 * An Interface for Entities that are owned by a User, indicated by a $user Entity member, and have the related
 * getUser() getter method
 */
interface SystemComponent
{
    /**
     * Get the ID of the Component
     *
     * @return int
     */
    public function getId();

    /**
     * Get the owning User entity
     *
     * @return User
     */
    public function getUser();

    /**
     * Get the parent Entity of this one
     *
     * @return SystemComponent|null
     */
    public function getParent();
}

<?php

namespace App\Contracts;

use App\Entities\Base\User;

/**
 * An Interface for Entities that are owned by a User, indicated by a $user Entity member, and have the related
 * getUser() getter method
 */
interface SystemComponent
{
    /**
     * Get the ID of the Component
     *
     * @return int
     */
    public function getId();

    /**
     * Get the owning User entity
     *
     * @return User
     */
    public function getUser();

    /**
     * Set the owning User entity
     *
     * @param User $user
     */
    public function setUser(User $user);

    /**
     * Get the parent Entity of this one
     *
     * @return SystemComponent|null
     */
    public function getParent();
}

Add setUser() method to the contract

Add setUser() method to the contract


<?php

namespace Oro\Bundle\JsFormValidationBundle\Tests\Unit\DependencyInjection;

use Oro\Bundle\JsFormValidation\DependencyInjection\Configuration;

class ConfigurationTest extends \PHPUnit_Framework_TestCase
{
    public function testGetConfigTreeBuilder()
    {
        $configuration = new Configuration();
        $builder = $configuration->getConfigTreeBuilder();
        $this->assertInstanceOf('Symfony\Component\Config\Definition\Builder\TreeBuilder', $builder);
    }
}

<?php

namespace Oro\Bundle\JsFormValidationBundle\Tests\Unit\DependencyInjection;

use Oro\Bundle\JsFormValidationBundle\DependencyInjection\Configuration;

class ConfigurationTest extends \PHPUnit_Framework_TestCase
{
    public function testGetConfigTreeBuilder()
    {
        $configuration = new Configuration();
        $builder = $configuration->getConfigTreeBuilder();
        $this->assertInstanceOf('Symfony\Component\Config\Definition\Builder\TreeBuilder', $builder);
    }
}

BAP-769: Create OroJsFormValidationBundle and add dependency on APYJsFormValidationBundle
- fixed invalid import class name


<?php

    include("/home/c0smic/secure/data_db_settings.php");

    $body = file_get_contents('php://input');
    $xml = simplexml_load_file($body);

    # Read GET variables
    $stime = $xml->data->stime;
    $etime = $xml->data->etime;
    $moves = $xml->data->moves;

    $conn = mysql_connect('localhost:3036', $dbuser, $dbpass);
    if(! $conn )
    {
        die('Could not connect: ' . mysql_error());
    }
    unset($dbuser, $dbpass);

    mysql_select_db('c0smic_maze-game');

    $sql= "INSERT INTO data (stime, etime, moves)
    VALUES
    ('$stime','$etime','$moves')";

    $retval = mysql_query( $sql, $conn );
    if(! $retval )
    {
        die('Could not enter data: ' . mysql_error());
    }

    mysql_close($conn);
    echo $str;

?>

<?php

    include("/home/c0smic/secure/data_db_settings.php");

    //$body = file_get_contents('php://input');
    $xml = simplexml_load_file('php://input');

    # Read GET variables
    $stime = $xml->data->stime;
    $etime = $xml->data->etime;
    $moves = $xml->data->moves;

    $conn = mysql_connect('localhost:3036', $dbuser, $dbpass);
    if(! $conn )
    {
        die('Could not connect: ' . mysql_error());
    }
    unset($dbuser, $dbpass);

    mysql_select_db('c0smic_maze-game');

    $sql= "INSERT INTO data (stime, etime, moves)
    VALUES
    ('$stime','$etime','$moves')";

    $retval = mysql_query( $sql, $conn );
    if(! $retval )
    {
        die('Could not enter data: ' . mysql_error());
    }

    mysql_close($conn);
    echo $str;

?>

Load input directly to simplexml

Load input directly to simplexml