<?php

/* (c) Jad Bitar <jadb@cakephp.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

require_once __DIR__ . '/common.php';

/**
 * CakePHP 3 Project Template configuration
 */

// CakePHP 3 Project Template shared dirs
set('shared_dirs', [
    'logs',
    'tmp',
]);

// CakePHP 3 Project Template shared files
set('shared_files', [
    'config/app.php',
]);

/**
 * Initialization
 */
task('deploy:init', function () {
    run('{{release_path}}/bin/cake orm_cache clear');
    run('{{release_path}}/bin/cake orm_cache build');
})->desc('Initialization');

/**
 * Run migrations
 */
task('deploy:run_migrations', function () {
    run('{{release_path}}/bin/cake migrations migrate');
})->desc('Run migrations');

/**
 * Main task
 */
task('deploy', [
    'deploy:prepare',
    'deploy:release',
    'deploy:update_code',
    'deploy:shared',
    'deploy:vendors',
    'deploy:init',
    'deploy:run_migrations',
    'deploy:symlink',
    'cleanup',
])->desc('Deploy your project');

after('deploy', 'success');

<?php

/* (c) Jad Bitar <jadb@cakephp.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

require_once __DIR__ . '/common.php';

/**
 * CakePHP 3 Project Template configuration
 */

// CakePHP 3 Project Template shared dirs
set('shared_dirs', [
    'logs',
    'tmp',
]);

// CakePHP 3 Project Template shared files
set('shared_files', [
    'config/app.php',
]);

/**
 * Create plugins' symlinks
 */
task('deploy:init', function () {
    run('{{release_path}}/bin/cake plugin assets symlink');
})->desc('Initialization');

/**
 * Run migrations
 */
task('deploy:run_migrations', function () {
    run('{{release_path}}/bin/cake migrations migrate');
    run('{{release_path}}/bin/cake orm_cache clear');
    run('{{release_path}}/bin/cake orm_cache build');
})->desc('Run migrations');

/**
 * Main task
 */
task('deploy', [
    'deploy:prepare',
    'deploy:release',
    'deploy:update_code',
    'deploy:shared',
    'deploy:vendors',
    'deploy:init',
    'deploy:run_migrations',
    'deploy:symlink',
    'cleanup',
])->desc('Deploy your project');

after('deploy', 'success');

Add plugin symlink, move cache post-migration


<?php

namespace Predis\Pipeline;

use Predis\Network\IConnection;

class FireAndForgetExecutor implements IPipelineExecutor {
    public function execute(IConnection $connection, &$commands) {
        foreach ($commands as $command) {
            $connection->writeCommand($command);
        }
        $connection->disconnect();

        return array();
    }
}

Add a fire-and-forget executor for pipelines.


<?php

namespace HCLabs\ModelManagerBundle\Exception;

class ModelManagerNotFoundException extends \Exception
{
    public function __construct($class = null)
    {
        if (is_object($class)) {
            $class = get_class($class);
        }

        $message = sprintf('Model Manager for class \'%s\' not found.', $class);

        parent::__construct($message);
    }
}

Add a manager not found exception

[Exception] Add a manager not found exception


<?php
/**
 * This file is part of the bee4/transport package.
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright Bee4 2014
 * @author  Stephane HULARD <s.hulard@chstudio.fr>
 * @package Bee4\Transport
 */

namespace Bee4\Transport;

use Bee4\Transport\Message\Request\AbstractRequest;

/**
 * Http client canvas
 * @package Bee4\Transport
 */
interface ClientInterface
{
	/**
	 * Send the request
	 * @param AbstractRequest $request The request to be send
	 * @return Message\Response
	 * @throws \Exception
	 */
	public function send( AbstractRequest $request );

	/**
	 * Create the request object
	 * @param string $method
	 * @param string $url
	 * @param array $headers
	 * @return AbstractRequest
	 */
	public function createRequest( $method, $url = '', array $headers = [] );
}

Add a new Interface to define Client contract

Signed-off-by: Stéphane HULARD <a24f38cb8c57ec2778c80a9f0c151933508927e5@chstudio.fr>


<?php

namespace Rjeny\Jira\Entities;

use Rjeny\Jira\Fields;
use Rjeny\Jira\Fields\BaseAbstractField;
use Rjeny\Jira\JiraException;
use Rjeny\Jira\JiraClient;
use Rjeny\Jira\Entities\Issue\IssueAttachment;

/**
 * Class for User entity
 *
 * @package Rjeny\Jira\Entities
 *
 */
class User extends BaseAbstractEntity
{
    protected $name = 'user';

    function __construct(JiraClient $client, $key=null)
    {
        parent::__construct($client);
    }

    /**
     * @return array
     */
    public function prepareRequestData()
    {
        return [];
    }

    public function getUrl()
    {
        // TODO: Implement getUrl() method.
    }

    /**
     * Data setter
     * TODO: setValue для всех полей по человечески
     *
     * @param $key
     * @param $value
     * @return bool
     */
    function __set($key, $value)
   {
        return false;
   }

   public function setData($key, $value)
   {
       return false;
   }

    /**
     * Saving object on Jira
     */
    public function save()
   {
       if ($this->key || $this->id) {
           $this->update();
       } else {
           $this->create();
       }
   }

    /**
     * Set request for create
     */
    protected function create() {
        $response   = $this->client->sendRequest('POST', $this->name, $this->prepareRequestData());

        $this->id   = $response['id'];
        $this->key  = $response['key'];
        $this->self = $response['self'];
   }

    /**
     * Set request for update
     */
    protected function update() {
        $this->client->sendRequest('POST', $this->name . ($this->key ? : (string) $this->id), $this->prepareRequestData());
    }

    /**
     * Get user
     *
     * @param JiraClient $client
     * @param            $key
     *
     * @return User
     */
    public static function getCurrent(JiraClient $client, $key)
    {
        $user = new User($client);

        $user->key=$key;
        $response = $client->sendRequest('GET', 'user', ['key' => $key]);

        return $response;
    }
}

Add user entity (now just only for getting user info)


<?php
namespace PhpSigep\Pdf\Chancela;

use PhpSigep\Pdf\Script\Elipse;

/**
 * @author: Stavarengo
 */
class Carta2016 extends AbstractChancela
{

    public function draw(\PhpSigep\Pdf\ImprovedFPDF $pdf)
    {
        $pdf->saveState();

        // quantos mm cabem dentro de um pt do pdf
        $un = 72 / 25.4;

        // Desenha o elipse
        $k         = $pdf->k;
        $wRect     = $un * 30 / $k;
        $h         = $un * 28 / $k;
        $lineWidth = 2 / $k;
        $pdf->SetLineWidth($lineWidth);
        $x      = $this->x;
        $y      = $this->y;
        $rx     = $wRect / 2;
        $ry     = $h / 2;
        $elipse = new Elipse();
        $pdf->SetDrawColor(0, 0, 0);
        $elipse->ellipse($pdf, $x, $y, $rx, $ry);

        // Escreve o texto
        $pdf->SetFont('Arial', 'BI');
        $pdf->SetXY($x, $y + 10 / $k);
        $fontSize = 15;
        $texto    = 'Carta';
        $pdf->SetFontSize($fontSize);
        $pdf->Cell($wRect, 23 / $k, $texto, 0, 2, 'C');

        // Número contrato e DR
        $pdf->SetFont('', '', 7);
        $texto = $this->accessData->getNumeroContrato() . '/' . $this->accessData->getAnoContrato(
            ) . '-DR/' . $this->accessData->getDiretoria()->getSigla();
        $pdf->Cell($wRect, 6 / $k, $texto, 0, 2, 'C');

        // Nome do remetente
        $pdf->SetFont('', 'B', 9);
        $pdf->MultiCell($wRect, 9 / $k, $pdf->_($this->nomeRemetente), 0, 'C');

        // Insere a logo do correios na parte inferior
        $pdf->SetDrawColor(255, 255, 255);
        $pdf->SetLineWidth(15 / $k);
        $x1 = $x + 24.5 / $k;
        $x2 = $x1 + $pdf->GetStringWidth('CORREIOS') - 9.5 / $k;
        $y1 = $y + $h - 6 / $k;
        $pdf->Image(realpath(dirname(__FILE__)) . '/../correios-logo.png', $x1 - 2 , $y1 - 5);

        $pdf->restoreLastState();
    }

}

Add novo layout para cartas.

Add novo layout para cartas.


<?php

namespace Application\Controller;

use Application\Controller\IndexController;
use Zend\Http\Request;
use Zend\Http\Response;
use Zend\Mvc\MvcEvent;
use Zend\Mvc\Router\RouteMatch;
use PHPUnit_Framework_TestCase;
use Zend\Mvc\Application;

class IndexControllerFailTest extends PHPUnit_Framework_TestCase
{
    protected $controller;
    protected $request;
    protected $response;
    protected $routeMatch;
    protected $event;

    protected function setUp()
    {
        $bootstrap = Application::init(include 'tests/unit/test.config.php');
        $this->controller = new IndexController();
        $this->request = new Request();
        $this->routeMatch = new RouteMatch(array('controller' => 'index'));
        $this->event = $bootstrap->getMvcEvent();
        $this->event->setRouteMatch($this->routeMatch);
        $this->controller->setEvent($this->event);
        $this->controller->setEventManager($bootstrap->getEventManager());
        $this->controller->setServiceLocator($bootstrap->getServiceManager());
    }

    public function testIndexActionCannotBeAccessed()
    {
     $this->routeMatch->setParam('action', 'index');

     $result = $this->controller->dispatch($this->request);
     $response = $this->controller->getResponse();

     $this->assertEquals(404, $response->getStatusCode());
     $this->assertInstanceOf('Zend\View\Model\ViewModel', $result);
    }
}

Test file to check failure on jenkins

Test file to check failure on jenkins


<?php
	// TO-DO: make sure GET score is valid format, GET pass is valid password for user, and file (post) 'score' exists

	include("includes/sql.php");

	$score = explode(":", $_GET['score']);
	$stmt = $db->prepare("INSERT INTO scores
	(
		`maphash`,
		`user`,
		`submithash`,
		`300s`,
		`100s`,
		`50s`,
		`geki`,
		`katu`,
		`misses`,
		`score`,
		`maxcombo`,
		`perfect`,
		`mods`,
		`passed`,
		`grade`
	)
	VALUES(
		:maphash,
		:user,
		:submithash,
		:300s,
		:100s,
		:50s,
		:geki,
		:katu,
		:misses,
		:score,
		:maxcombo,
		:perfect,
		:mods,
		:passed,
		:grade
	);");

	//print_r($score);

	$passed = 0;
	if($score[14] == "True") {
		$passed = 1;
	}

	$perfect = 0;
	if($score[11] == "True") {
		$perfect = 1;
	}

	$stmt->bindParam(":maphash", $score[0], PDO::PARAM_STR);
	$stmt->bindParam(":user", $score[1], PDO::PARAM_STR);
	$stmt->bindParam(":submithash", $score[2], PDO::PARAM_STR);
	$stmt->bindParam(":300s", $score[3], PDO::PARAM_INT);
	$stmt->bindParam(":100s", $score[4], PDO::PARAM_INT);
	$stmt->bindParam(":50s", $score[5], PDO::PARAM_INT);
	$stmt->bindParam(":geki", $score[6], PDO::PARAM_INT);
	$stmt->bindParam(":katu", $score[7], PDO::PARAM_INT);
	$stmt->bindParam(":misses", $score[8], PDO::PARAM_INT);
	$stmt->bindParam(":score", $score[9], PDO::PARAM_INT);
	$stmt->bindParam(":maxcombo", $score[10], PDO::PARAM_INT);
	$stmt->bindParam(":perfect", $perfect, PDO::PARAM_INT);
	$stmt->bindParam(":mods", $score[13], PDO::PARAM_STR);
	$stmt->bindParam(":passed", $passed, PDO::PARAM_STR);
	$stmt->bindParam(":grade", $score[12], PDO::PARAM_STR);
	$stmt->execute();

	$newid = $db->lastInsertId();

	move_uploaded_file($_FILES['score']['tmp_name'], __DIR__ . "/replays/" . $newid);
?>

Create initial score submit file

Create initial score submit file


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints as Assert;
use Listabierta\Bundle\MunicipalesBundle\Validator\Constraints\DNI;

class CandidateStepVerifyType extends AbstractType
{
	public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('continue', 'submit', array('attr' => array('class' => 'submit')));
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    }

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

Add candidate step verify type

Add candidate step verify type


    <?php $base_url = URL::site(NULL, TRUE);
    ?>

Hi <?= ucfirst($name); ?>,

Your profile was successfully created in KRCFM

Please click the below link to activate your account

<a href="<?= $url; ?>?user_id=<?= $user_id; ?>"><?= $url; ?>?user_id=<?= $user_id; ?>

Regards,
KRCFM Team

Create a new mail template for Profile activation


<?php

namespace Laratrust\Tests\Migrations;

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

class OthersMigration extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('others', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->rememberToken();
            $table->timestamps();
            $table->softDeletes();
        });
    }

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

Add migration to new model called other

Add migration to new model called other


<?php

use yii\db\Schema;
use yii\db\Migration;

class m130524_201442_init extends Migration
{
    public function up()
    {

    }

    public function down()
    {

    }
}

Fix migrate error on hhvm

Fix migrate error on hhvm


<?php
/**
 * @package BC Security
 */

namespace BlueChip\Security\Tests\Unit\Cases\Modules\Log;

use Brain\Monkey\Actions;
use BlueChip\Security\Modules\Log;

class EventsMonitorTest extends \BlueChip\Security\Tests\Unit\TestCase
{
    /**
     * @var \BlueChip\Security\Modules\Log\EventsMonitor
     */
    private $monitor;

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

        $this->monitor = new Log\EventsMonitor('1.2.3.4', '5.6.7.8');
    }

    public function testBadCookie()
    {
        Actions\expectDone(Log\Action::EVENT)->once()->with(\Mockery::type(Log\Events\AuthBadCookie::class));

        $this->monitor->logBadCookie(['username' => 'test-user']);
    }

    public function testCoreChecksumsVerificationAlert()
    {
        Actions\expectDone(Log\Action::EVENT)->once()->with(\Mockery::type(Log\Events\CoreChecksumsVerificationAlert::class));

        $this->monitor->logCoreChecksumsVerificationAlert([], []);
    }

    public function testFailedLogin()
    {
        Actions\expectDone(Log\Action::EVENT)->once()->with(\Mockery::type(Log\Events\LoginFailure::class));

        $this->monitor->logFailedLogin('test-user');
    }

    public function testLoginLockout()
    {
        Actions\expectDone(Log\Action::EVENT)->once()->with(\Mockery::type(Log\Events\LoginLockout::class));

        $this->monitor->logLockoutEvent('4.3.2.1', 'test-user', 600);
    }

    public function testPluginChecksumsVerificationAlert()
    {
        // No plugins with alert to report...
        $plugins = [];
        // ... so no event should be recorded.
        Actions\expectDone(Log\Action::EVENT)->never()->with(\Mockery::type(Log\Events\PluginChecksumsVerificationAlert::class));

        $this->monitor->logPluginChecksumsVerificationAlert($plugins);
    }

    public function testSuccessfulLogin()
    {
        Actions\expectDone(Log\Action::EVENT)->once()->with(\Mockery::type(Log\Events\LoginSuccessful::class));

        $this->monitor->logSuccessfulLogin('test-user');
    }
}

Add some basic unit tests for EventsMonitor.


<?php

/*
 * Copyright (C) 2017 Mandelkow
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

require_once 'default.php';

$sql_query = "SELECT TABLE_NAME FROM `TABLES` WHERE `TABLE_SCHEMA` = " . $config['database_name'];
mysqli_query_verbose($sql_query);
while ($row = mysqli_fetch_object($ergebnis)) {
    $Table_names[] = $row->TABLE_NAME;
    echo "Found table $row->TABLE_NAME
\n";
}

foreach ($Table_names as $key => $table_name){
    echo "Working on $table_name...
\n";
    $backup_file = get_root_folder() . "tmp/$table_name.sql";
    $sql = "SELECT * INTO OUTFILE '$backup_file' FROM $table_name";
}

Backup of all the database tables. Each in a seperate file.


<?php
/**
* @author yooper(dcardin2007@gmail.com)
* Loads a text file into memory
* @usage  $stopWords = StopWordFactory::get('stop-words-fox.txt');
*/

class StopWordFactory
{
    /**
    *
    * @returns array The array is empty if the stop words file does not exist
    */
    static public function get($fileName)
    {
	    $path = realpath(__DIR__.'/data/'.basename($fileName));
        if(file_exists($path)) {
            return array_map('trim', file($path));
        }
        return [];
    }
}

Add stop words php factory

Add stop words php factory


<?php

namespace SimplyTestable\ApiBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class NormalisePublicUserJobVisibility extends AbstractFixture implements OrderedFixtureInterface, ContainerAwareInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    /**
     * {@inheritDoc}
     */
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    /**
     * {@inheritDoc}
     */
    public function load(ObjectManager $manager)
    {
        $jobRepository = $manager->getRepository('SimplyTestable\ApiBundle\Entity\Job\Job');
        $publicUserPrivateJobs = $jobRepository->findBy(array(
            'user' => $this->container->get('simplytestable.services.userservice')->getPublicUser(),
            'isPublic' => false
        ));

        if (count($publicUserPrivateJobs) === 0) {
            return true;
        }

        foreach ($publicUserPrivateJobs as $job) {
            $job->setIsPublic(true);
            $manager->persist($job);
        }

        $manager->flush();
    }

    /**
     * {@inheritDoc}
     */
    public function getOrder()
    {
        return 9; // the order in which fixtures will be loaded
    }
}

Add fixture to set public job isPublic=true for historical jobs


<?php
// Jivoo
// Copyright (c) 2015 Niels Sonnich Poulsen (http://nielssp.dk)
// Licensed under the MIT license.
// See the LICENSE file or http://opensource.org/licenses/MIT for more information.
namespace Jivoo\Data;

/**
 * An array with a predicate.
 */
class PredicateArray implements \ArrayAccess, \Countable, \Iterator {
  /**
   * @var array
   */
  private $original;

  /**
   * @var callable
   */
  private $predicate;

  private $array = array();

  public function __construct($array, $predicate) {
    $this->original = $array;
    $this->predicate = $predicate;
  }

  /**
   * {@inheritDoc}
   */
  public function offsetExists($offset) {
    if (isset($this->array[$offset]))
      return true;
    if (isset($this->original[$offset])) {
      if (call_user_func($this->predicate, $this->original[$offset])) {
        $this->array[$offset] = $this->original[$offset];
        return true;
      }
    }
    return false;
  }

  /**
   * {@inheritDoc}
   */
  public function offsetGet($offset) {
    if (isset($this->array[$offset]))
      return $this->array[$offset];
    if (isset($this->original[$offset])) {
      if (call_user_func($this->predicate, $this->original[$offset])) {
        $this->array[$offset] = $this->original[$offset];
        return $this->array[$offset];
      }
    }
    return null;
  }

  /**
   * {@inheritDoc}
   */
  public function offsetSet($offset, $value) {
    $this->array[$offset] = $value;
  }

  /**
   * {@inheritDoc}
   */
  public function offsetUnset($offset) {
    if (isset($this->array[$offset]))
      unset($this->array[$offset]);
    if (isset($this->original[$offset]))
      unset($this->original[$offset]);
  }

  /**
   * {@inheritDoc}
   */
  public function current() {
    return current($this->original);
  }

  /**
   * {@inheritDoc}
   */
  public function key() {
    return key($this->original);
  }

  /**
   * {@inheritDoc}
   */
  public function next() {
    while (true) {
      next($this->original);
      if (key($this->original) === null)
        break;
      if (call_user_func($this->predicate, current($this->original)))
        break;
    }
  }

  /**
   * {@inheritDoc}
   */
  public function rewind() {
    reset($this->original);
  }

  /**
   * {@inheritDoc}
   */
  public function valid() {
    return key($this->original) !== null;
  }

  /**
   * {@inheritDoc}
   */
  public function count() {

  }
}

Add predicate array for query processors.


<?

$table = array_fill(0, 1000, array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5, "f"=>6, "g"=>7, "h"=>8, "i"=>9, "j"=>10));

function test_bigtable($table)
{
ob_start();
?>

<?
foreach($table as $rowNum => $row)
{
?>

<?
foreach($row as $value)
{
?>
<? echo $value; ?>
<?
}
?>

<?
}
?>

<?
return ob_get_clean();
}

$request_count = 1000;

$start = microtime(true);
for ($i = 0; $i < $request_count; $i++)
{
  test_bigtable($table);
}
$elapsed = microtime(true) - $start;
$time_per_request = ($elapsed / $request_count) * 1000;
echo "PHP: $time_per_request ms\n";
?>

Add bigtable benchmark in PHP.

Add bigtable benchmark in PHP.


<?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.
 */

namespace Flarum\Api\Middleware;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Zend\Stratigility\MiddlewareInterface;

class FakeHttpMethods implements MiddlewareInterface
{
    /**
     * {@inheritdoc}
     */
    public function __invoke(Request $request, Response $response, callable $out = null)
    {
        if ($request->getMethod() === 'POST' && $request->hasHeader('x-http-method')) {
            $fakeMethod = $request->getHeaderLine('x-http-method');

            $request = $request->withMethod(strtoupper($fakeMethod));
        }

        return $out ? $out($request, $response) : $response;
    }
}

Implement middleware for faking HTTP methods

Refs #502.


<?php

use Illuminate\Database\Migrations\Migration;

class AddBccColumnEmailLog extends Migration {
	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up() {
		Schema::table('email_log', function ($table) {
			$table->string('to')->nullable()->change();
			$table->string('bcc')->after('to')->nullable();
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down() {
		Schema::table('email_log', function ($table) {
			$table->string('to')->change();
			$table->droPColumn('bcc');
		});
	}
}

Add bcc column in table

Add bcc column in table

Add bcc column to bcc address


<?php

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

class ChangeTypeToTextOfHeadlineColumnOfEntries extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('entries', function (Blueprint $table) {
            $table->text('headline')->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('entries', function (Blueprint $table) {
            $table->string('headline')->change();
        });
    }
}

Change column type to text of entries.headline


<?php

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

class PurgeEmptyCellsFromDatabase extends Migration
{
    public function up()
    {
        DB::statement("DELETE FROM data_values WHERE value='';");
    }
}

Purge empty values from database

Purge empty values from database


<?php

namespace AbleCore\Install\Helpers\Fields;

use AbleCore\Install\Helpers\Field;
use AbleCore\Install\Helpers\FieldTypes;

class TermReferenceField extends Field {

	public function setType($type = FieldTypes::TERM_REFERENCE)
	{
		return parent::setType($type);
	}

	/**
	 * Defines which vocabulary the term reference field references.
	 *
	 * @param string $vocabulary The machine name of the vocabulary.
	 * @param int    $parent     The TID of the parent term.
	 *
	 * @return $this
	 */
	public function references($vocabulary, $parent = 0)
	{
		return $this->setSetting('allowed_values', array(array(
			'vocabulary' => $vocabulary,
			'parent' => $parent,
		)));
	}

}

Add the term reference field.

Add the term reference field.


<?php

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

class AddAcronymToCourts extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('courts', function($table) {
            $table->string('acronym', 5)->nullable();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('courts', function($table) {
            $table->dropColumn('acronym');
        });
    }
}

Add migration acronym for courts

Add migration acronym for courts


<?php

namespace mageekguy\atoum;

class configurator
{
	protected $script = null;
	protected $methods = array();

	public function __construct(scripts\runner $script)
	{
		$this->script = $script;

		foreach ($this->script->getHelp() as $help)
		{
			list($arguments, $values) = $help;

			foreach ($arguments as $argument)
			{
				$this->methods[preg_replace('/-(.)/e', 'ucfirst(\'\1\')', ltrim($argument, '-'))] = $argument;
			}
		}
	}

	public function __call($method, $arguments)
	{
		if (isset($this->methods[$method]) === true)
		{
			$this->script->getArgumentsParser()->invokeHandlers($this->script, $this->methods[$method], $arguments);

			return $this;
		}
		else
		{
			if (method_exists($this->script, $method) === false)
			{
				throw new exceptions\runtime\unexpectedValue('Method \'' . $method . '\' is unavailable');
			}

			$return = call_user_func_array(array($this->script, $method), $arguments);

			return ($return === $this->script ? $this : $return);
		}
	}

	public function getScript()
	{
		return $this->script;
	}
}

<?php

namespace mageekguy\atoum;

class configurator
{
	protected $script = null;
	protected $methods = array();

	public function __construct(scripts\runner $script)
	{
		$this->script = $script;

		foreach ($this->script->getHelp() as $help)
		{
			list($arguments, $values) = $help;

			foreach ($arguments as $argument)
			{
				$this->methods[preg_replace_callback('/-(.)/', function($matches) { return ucfirst($matches[1]); }, ltrim($argument, '-'))] = $argument;
			}
		}
	}

	public function __call($method, $arguments)
	{
		if (isset($this->methods[$method]) === true)
		{
			$this->script->getArgumentsParser()->invokeHandlers($this->script, $this->methods[$method], $arguments);

			return $this;
		}
		else
		{
			if (method_exists($this->script, $method) === false)
			{
				throw new exceptions\runtime\unexpectedValue('Method \'' . $method . '\' is unavailable');
			}

			$return = call_user_func_array(array($this->script, $method), $arguments);

			return ($return === $this->script ? $this : $return);
		}
	}

	public function getScript()
	{
		return $this->script;
	}
}

Use preg_replace_callback instead of \e to avoid an E_DEPRECATED on php-5.5alpha


<?php

// default path
env('bin/typo3cms', 'bin/typo3cms');

task('typo3cms:cache:flush_forced', function() {
    run("{{bin/typo3cms}} cache:flush --force");
})->desc('flush caches forced');

task('typo3cms:database:updateschema', function() {
    run("{{bin/typo3cms}} database:updateschema \"*.add,*.change\"");
})->desc('update database schema');

task('typo3cms:install:generatepackagestates', function() {
    run("{{bin/typo3cms}} install:generatepackagestates");
})->desc('generate packagestates file');

Add TYPO3 recipe with tasks

Add TYPO3 recipe with tasks

* typo3cms:cache:flush_forced
* typo3cms:database:updateschema
* typo3cms:install:generatepackagestates


<?php

namespace Blogger\BlogBundle\Twig\Extensions;

class BloggerBlogExtension extends \Twig_Extension
{
    public function getFilters()
    {
        return array(
            'created_ago' => new \Twig_Filter_Method($this, 'createdAgo'),
        );
    }

    public function createdAgo(\DateTime $dateTime)
    {
        $delta = time() - $dateTime->getTimestamp();
        if ($delta < 0)
            throw new \InvalidArgumentException("createdAgo is unable to handle dates in the future");

        $duration = "";
        if ($delta < 60)
        {
            // Seconds
            $time = $delta;
            $duration = $time . " second" . (($time > 1) ? "s" : "") . " ago";
        }
        else if ($delta <= 3600)
        {
            // Mins
            $time = floor($delta / 60);
            $duration = $time . " minute" . (($time > 1) ? "s" : "") . " ago";
        }
        else if ($delta <= 86400)
        {
            // Hours
            $time = floor($delta / 3600);
            $duration = $time . " hour" . (($time > 1) ? "s" : "") . " ago";
        }
        else
        {
            // Days
            $time = floor($delta / 86400);
            $duration = $time . " day" . (($time > 1) ? "s" : "") . " ago";
        }

        return $duration;
    }

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

Create a file for Twig extension

Create a file for Twig extension


<?php

namespace Tests\AppBundle\Command;

use AppBundle\Command\CreateTraitFormatCommand;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Console\Tester\CommandTester;

class CreateTraitFormatCommandTest extends KernelTestCase
{
    public function testExecute()
    {
        self::bootKernel();

        $em = self::$kernel->getContainer()->get('app.orm')->getDefaultManager();
        $testFormat = $em->getRepository('AppBundle:TraitFormat')->findOneBy(array(
            'format' => 'TestFormat'
        ));
        $this->assertNull($testFormat, 'Before creation the "TestFormat" does not exist.');

        $application = new Application(self::$kernel);

        $application->add(new CreateTraitFormatCommand());

        $command = $application->find('app:create-traitformat');
        $commandTester = new CommandTester($command);
        $args = array(
            'command'  => $command->getName(),
            'format' => 'TestFormat'
        );
        $commandTester->execute($args);

        // the output of the command in the console
        $output = $commandTester->getDisplay();
        $this->assertContains('TraitFormat successfully created', $output);

        $testFormat = $em->getRepository('AppBundle:TraitFormat')->findOneBy(array(
            'format' => 'TestFormat'
        ));
        $this->assertNotNull($testFormat, 'After creation the "TestFormat" does exist.');
        $this->assertEquals('TestFormat', $testFormat->getFormat());

        $commandTester->execute($args);
        $output = $commandTester->getDisplay();
        $this->assertContains('TraitFormat already exists, nothing to do.', $output);
    }
}

Add test for add-traitformat command

Add test for add-traitformat command


<?php
namespace atk4\core;

/**
 * Extend Psysh to display ATK Exceptions nicely by adding into
 * ~/.config/psysh/config.php
 *
 * return [ 'commands' => [ new \atk4\core\PsyshE  ] ];
 *
 * If this file fails to load, add this line above return:
 *
 * include '/path/to/atk4/core/PsyshE.php';
 *
 * If Agile Exception is thrown, you can get a nice output
 * by typing
 *
 * >>> e
 *
 */

use Psy\Context;
use Psy\Command\TraceCommand;
use Psy\ContextAware;
use Psy\Output\ShellOutput;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class PsyshE extends TraceCommand implements ContextAware {
    protected $context;
    public function setContext(Context $context)
    {
        $this->context = $context;
    }

    protected function configure()
    {
        $this
            ->setName('e')
            ->setDescription('Nicely display Agile Exceptions')
            ->setHelp(
                <<<'HELP'
Display ATK exceptions nicely
HELP
            );
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $exception = $this->context->getLastException();
        if (!$exception instanceof \atk4\core\Exception) {
            throw new \InvalidArgumentException('Last exception wasn\'t Agile Exception. use wtf');
        }
        $output->write($exception->getColorfulText());
        /*
        $count     = $input->getOption('verbose') ? PHP_INT_MAX : pow(2, max(0, (strlen($incredulity) - 1)));

        $trace     = $this->getBacktrace($exception, $count);
        $shell = $this->getApplication();
        $output->page(function ($output) use ($exception, $trace, $shell) {
            $shell->renderException($exception, $output);
            $output->writeln('--');
            $output->write($trace, true, ShellOutput::NUMBER_LINES);
        });
         */
    }

}

Add implementation for 'e' commant in Psysh


<?php

namespace Tests\Regis\Application\Repository;

use Regis\Application\Entity;
use Regis\Application\Repository\InMemoryRepositories;

class InMemoryRepositoriesTest extends \PHPUnit_Framework_TestCase
{
    public function testFindAllAGeneratorToTheRepositories()
    {
        $repo = new InMemoryRepositories([
            'some identifier' => [
                'secret' => 'shared secret',
            ]
        ]);

        $this->assertInstanceOf(\Generator::class, $result = $repo->findAll());
        $this->assertCount(1, iterator_to_array($result));
    }

    /**
     * @expectedException \Regis\Application\Repository\Exception\NotFound
     */
    public function testFindThrowAnExceptionIfTheEntityDoesNotExist()
    {
        $repo = new InMemoryRepositories([
            'some identifier' => [
                'secret' => 'shared secret',
            ]
        ]);

        $repo->find('some identifier that does not exist');
    }

    public function testFindReturnsTheEntityIfItExists()
    {
        $repo = new InMemoryRepositories([
            'some identifier' => [
                'secret' => 'shared secret',
            ]
        ]);

        $entity = $repo->find('some identifier');

        $this->assertInstanceOf(Entity\Github\Repository::class, $entity);
        $this->assertSame('some identifier', $entity->getIdentifier());
        $this->assertSame('shared secret', $entity->getSharedSecret());
    }

    public function testARepositoryCanBeSaved()
    {
        $repo = new InMemoryRepositories([]);

        $entity = new Entity\Github\Repository('some identifier', 'shared secret');
        $repo->save($entity);

        $this->assertSame($entity, $repo->find('some identifier'));
    }
}

Add tests for the InMemoryRepositories repository


<?php
/*
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the MIT license.
 */

namespace OcraServiceManagerTest\DelegatorFactory;

use OcraServiceManager\DelegatorFactory\ServiceLocatorDelegatorFactory;
use OcraServiceManager\ServiceFactory\ApplicationFactory;
use stdClass;
use Zend\ServiceManager\ServiceManager;

use PHPUnit_Framework_TestCase;

/**
 * @author  Marco Pivetta <ocramius@gmail.com>
 * @license MIT
 */
class ServiceLocatorDelegatorFactoryTest extends PHPUnit_Framework_TestCase
{
    /**
     * @covers \OcraServiceManager\DelegatorFactory\ServiceLocatorDelegatorFactory
     */
    public function testProducesLocatorProxy()
    {
        $proxyFactory = $this->getMock('ProxyManager\\Factory\\AccessInterceptorScopeLocalizerFactory');
        $instance     = $this->getMock('Zend\\ServiceManager\\ServiceLocatorInterface');
        $proxyLocator = $this->getMock('Zend\\ServiceManager\\ServiceLocatorInterface');

        $proxyFactory
            ->expects($this->any())
            ->method('createProxy')
            ->with($instance, array(), array('foo'))
            ->will($this->returnValue($proxyLocator));

        $factory = new ServiceLocatorDelegatorFactory($proxyFactory, array('foo'));

        $this->assertSame(
            $proxyLocator,
            $factory->createDelegatorWithName(
                $this->getMock('Zend\\ServiceManager\\ServiceLocatorInterface'),
                'fooBar',
                'fooBaz',
                function () use ($instance) {
                    return $instance;
                }
            )
        );
    }

    /**
     * @covers \OcraServiceManager\DelegatorFactory\ServiceLocatorDelegatorFactory
     */
    public function testSkipsNonLocatorInstances()
    {
        $proxyFactory = $this->getMock('ProxyManager\\Factory\\AccessInterceptorScopeLocalizerFactory');
        $instance     = new stdClass();

        $factory = new ServiceLocatorDelegatorFactory($proxyFactory, array('foo'));

        $this->assertSame(
            $instance,
            $factory->createDelegatorWithName(
                $this->getMock('Zend\\ServiceManager\\ServiceLocatorInterface'),
                'fooBar',
                'fooBaz',
                function () use ($instance) {
                    return $instance;
                }
            )
        );
    }
}

Test coverage for the service locator delegator factory


<?php

namespace PHP_GCM;

class AggregateResultTest extends \PHPUnit_Framework_TestCase {

  public function testConstructsCorrectly() {
    $results = array();
    $results[] = new MulticastResult(1, 2, 1, 'multicast-id1', array());
    $results[] = new MulticastResult(1, 2, 1, 'multicast-id2', array());
    $results[] = new MulticastResult(1, 2, 1, 'multicast-id3', array());

    $aggregateResult = new AggregateResult($results);

    $this->assertEquals('multicast-id1', $aggregateResult->getMulticastId());
    $this->assertEquals(3, $aggregateResult->getSuccess());
    $this->assertEquals(9, $aggregateResult->getTotal());
    $this->assertEquals(6, $aggregateResult->getFailure());
    $this->assertEquals(3, $aggregateResult->getCanonicalIds());
    $this->assertTrue(is_array($aggregateResult->getResults()) && empty($aggregateResult->getResults()));
    $this->assertTrue(is_array($aggregateResult->getRetryMulticastIds()) && empty($aggregateResult->getRetryMulticastIds()));
  }

  public function testGetMulticastId() {
    $result = new MulticastResult(1, 2, 1, 'multicast-id', array());

    $this->assertEquals('multicast-id', $result->getMulticastId());
  }

  public function testGetSuccess() {
    $result = new MulticastResult(1, 2, 1, 'multicast-id', array());

    $this->assertEquals(1, $result->getSuccess());
  }

  public function testGetTotal() {
    $result = new MulticastResult(1, 2, 1, 'multicast-id', array());

    $this->assertEquals(3, $result->getTotal());
  }

  public function testGetFailure() {
    $result = new MulticastResult(1, 2, 1, 'multicast-id', array());

    $this->assertEquals(2, $result->getFailure());
  }

  public function testGetCanonicalIds() {
    $result = new MulticastResult(1, 2, 1, 'multicast-id', array());

    $this->assertEquals(1, $result->getCanonicalIds());
  }

  public function testGetResults() {
    $result = new MulticastResult(1, 2, 1, 'multicast-id', array());
    $result->addResult(new Result());

    $this->assertTrue(is_array($result->getResults()));
    $this->assertEquals(array(new Result()), $result->getResults());
  }

  public function testGetRetryMulticastIds() {
    $result = new MulticastResult(1, 2, 1, 'multicast-id', array(1));

    $this->assertEquals(array(1), $result->getRetryMulticastIds());
  }
}

Add test for AggregateResult class

Add test for AggregateResult class


<?php

/**
 * This class creates a new instance of a comment module
 * Modified by D.Cooper 2/23/2014
 */
class Commentmodule {

    private $CI;
    private $accidentid;
    private $userID;
    private $table = "";
    private $comment;

  /********************************************************************************/
    public function __construct($params) {
        $this->CI = &get_instance();
        $this->accidentid=$params['accidentid'];
        return $this->loadModule();

    }
/********************************************************************************/

    private function requestComments() {
        $this->CI->load->database();
        $sql = "SELECT * FROM comments WHERE accident_id=$this->accidentid ORDER BY comment_time DESC";
        $query = $this->CI->db->query($sql);
        return $query;
    }

    private function loadModule() {
        $now = time();
        $this->CI->load->helper('date');
        $query = $this->requestComments();
        echo '
';
        foreach ($query->result() as $comment) {
            echo '';
            echo '
Cooperd2      - '. timespan($comment->comment_time, $now).' ago
';
            echo '
' . $comment->message . '
 ';

            // echo  '

            //

Cooperd2

'.$comment->comment_date.'<Date</d>
'.$comment->message.'

';
        }
        echo '
';
    }

}

Create a comment module that creates a new instance of a comment feed.


<?php
    define('_DB_SERVER_', 'localhost');
    define('_DB_NAME_', 'DATABASE');
    define('_DB_USER_', 'USER');
    define('_DB_PASSWD_', 'PASSWORD');
    //define('_DB_FIRST_QUERY_', 'SET NAMES UTF8');
?>

Add exemple du fichier de configuration

Add exemple du fichier de configuration


<?php

return [
	'mirrors' => [
		'packagist' => [
			'url' => env('PACKAGIST_URL', 'https://packagist.org'),
		],
	],

	'github' => [
		'api' => [
			'username' => env('GITHUB_API_USERNAME'),
			'token'    => env('GITHUB_API_TOKEN'),
		],
	],
];

<?php

return [
	'mirrors' => [
		'cache' => [
			'url' => env('PACKAGIST_URL', 'https://packagist.org'),
		],
	],

	'github' => [
		'api' => [
			'username' => env('GITHUB_API_USERNAME'),
			'token'    => env('GITHUB_API_TOKEN'),
		],
	],
];

Rename packagist repo to cache

[TASK] Rename packagist repo to cache


<?php

/* best viewed through an atom viewer, such as http://inforss.mozdev.org/ */

require("config.inc.php");

$o = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_AUTHORIZATION);
try {
	$access_token_info = unserialize(file_get_contents(OAUTH_TMP_DIR . "/access_token_resp"));
	$o->setToken($access_token_info["oauth_token"],$access_token_info["oauth_token_secret"]);

	$feeds_url = "http://api.netflix.com/users/". oauth_urlencode($access_token_info["user_id"]) ."/feeds";
	$o->fetch($feeds_url);

	$feeds = $o->getLastResponse();

    /* we need to pick the rental history feed (returned rentals) */

    $feeds_xml = new SimpleXMLElement($feeds);

    /* if you want to access other feeds, change the following rel attribute */
    $feed_rel = "http://schemas.netflix.com/feed.rental_history.returned";

    $returned_feed = current($feeds_xml->xpath("/resource/link[@rel=\"{$feed_rel}\"]"))->attributes();

    $o->fetch($returned_feed["href"]);
	echo $o->getLastResponse();
} catch(OAuthException $E) {
	echo "Exception caught!\n";
	echo "Response: ". $E->lastResponse . "\n";
    var_dump($E);
}

<?php

/* best viewed through an atom viewer, such as http://inforss.mozdev.org/ */

require("config.inc.php");

$o = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET,OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_AUTHORIZATION);
try {
  $access_token_info = unserialize(file_get_contents(OAUTH_TMP_DIR . "/access_token_resp"));
  $o->setToken($access_token_info["oauth_token"],$access_token_info["oauth_token_secret"]);

  $feeds_url = "http://api.netflix.com/users/". oauth_urlencode($access_token_info["user_id"]) ."/feeds";
  $o->fetch($feeds_url);

  $feeds = $o->getLastResponse();

  /* we need to pick the rental history feed (returned rentals) */

  $feeds_xml = new SimpleXMLElement($feeds);

  /* if you want to access other feeds, change the following rel attribute */
  $feed_rel = "http://schemas.netflix.com/feed.rental_history.returned";

  $returned_feed = current($feeds_xml->xpath("/resource/link[@rel=\"{$feed_rel}\"]"))->attributes();

  /* don't sign the feed requests */
  $curl = curl_init($returned_feed["href"]);
  curl_exec($curl);
} catch(OAuthException $E) {
  echo "Exception caught!\n";
  echo "Response: ". $E->lastResponse . "\n";
  var_dump($E);
}

Update Netflix example (API request is no longer signed)

git-svn-id: 1d5fd79e00fb49afc950abd77d854b8070d085dd@299969 c90b9560-bf6c-de11-be94-00142212c4b1


<?php

namespace AdobeConnectClient\Tests\Commands;

use Exception;
use AdobeConnectClient\Commands\MeetingFeatureUpdate;

class MeetingFeatureUpdateTest extends TestCommandBase
{
    /**
     * return string
     */
    public function testExecute()
    {
        $command = new MeetingFeatureUpdate(1, 'feature', true);
        $command->setClient($this->client);

        $this->assertTrue($command->execute());

        return $this->client->getSession();
    }

    public function testException()
    {
        $this->expectException(Exception::class);

        $this->connection->overrideStatusWithNoAccess();

        $command = new MeetingFeatureUpdate(1, 'feature', true);
        $command->setClient($this->client);
        $command->execute();
    }
}

Create tests for MeetingFeatureUpdate command


<?php

use Illuminate\Database\Migrations\Migration;

class AddNewRankCacheColumns extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('osu_user_stats', function ($table) {
            $table->mediumInteger('xh_rank_count')->default(0)->after('x_rank_count');
            $table->mediumInteger('sh_rank_count')->default(0)->after('s_rank_count');
        });

        Schema::table('osu_user_stats_taiko', function ($table) {
            $table->mediumInteger('xh_rank_count')->default(0)->after('x_rank_count');
            $table->mediumInteger('sh_rank_count')->default(0)->after('s_rank_count');
        });

        Schema::table('osu_user_stats_fruits', function ($table) {
            $table->mediumInteger('xh_rank_count')->default(0)->after('x_rank_count');
            $table->mediumInteger('sh_rank_count')->default(0)->after('s_rank_count');
        });

        Schema::table('osu_user_stats_mania', function ($table) {
            $table->mediumInteger('xh_rank_count')->default(0)->after('x_rank_count');
            $table->mediumInteger('sh_rank_count')->default(0)->after('s_rank_count');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('osu_user_stats', function (Blueprint $table) {
            $table->dropColumn('xh_rank_count');
            $table->dropColumn('sh_rank_count');
        });

        Schema::table('osu_user_stats_taiko', function (Blueprint $table) {
            $table->dropColumn('xh_rank_count');
            $table->dropColumn('sh_rank_count');
        });

        Schema::table('osu_user_stats_fruits', function (Blueprint $table) {
            $table->dropColumn('xh_rank_count');
            $table->dropColumn('sh_rank_count');
        });

        Schema::table('osu_user_stats_mania', function (Blueprint $table) {
            $table->dropColumn('xh_rank_count');
            $table->dropColumn('sh_rank_count');
        });
    }
}

Add migration for new rank cache columns


<?php
namespace pyd\testkit\web\driver;

/**
 * Description of ChromeDriver
 *
 * @warning temporary class to manager client for chromedriver
 * @todo remove if not used
 *
 * @author Pierre-Yves DELETTRE <pierre.yves.delettre@gmail.com>
 */
class ChromeDriver extends RemoteDriver
{
    protected static $executable = '/usr/bin/chromedriver';

    protected static $port = 9515;

    public static function start(\DesiredCapabilities $desired_capabilities = null, \ChromeDriverService $service = null)
    {
        if ($desired_capabilities === null) {
          $desired_capabilities = \DesiredCapabilities::chrome();
        }

        if ($service === null) {
          $service = $this->getService();
        }

        $executor = new \DriverCommandExecutor($service);
        $driver = new static();
        $driver->setCommandExecutor($executor)
               ->startSession($desired_capabilities);
        return $driver;
    }

    public function startSession($desired_capabilities) {
        $command = new \WebDriverCommand(
          null,
          \DriverCommand::NEW_SESSION,
          array(
            'desiredCapabilities' => $desired_capabilities->toArray(),
          )
        );
        $response = $this->executor->execute($command);
        $this->setSessionID($response->getSessionID());
    }

    /**
     * @return \DriverService
     */
    protected function getService()
    {
        return new \DriverService($this->executable, $this->port, "--port=$this->port");
    }
}

Add a client for chromedriver with no use for now


<?php

/*
 * This file is part of Bens Penhorados, an undergraduate capstone project.
 *
 * (c) Fábio Santos <ffsantos92@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace App\Http\Controllers;

use App\Models\Attributes\Vehicle\VehicleCategory;
use App\Models\Attributes\Vehicle\VehicleColor;
use App\Models\Attributes\Vehicle\VehicleFuel;
use App\Models\Attributes\Vehicle\VehicleMake;
use App\Models\Attributes\Vehicle\VehicleModel;
use App\Models\Attributes\Vehicle\VehicleType;
use Illuminate\Http\Request;

/**
 * This is the vehicle filtering attributes controller class.
 *
 * @author Fábio Santos <ffsantos92@gmail.com>
 */
class VehicleFilteringAttributesController extends Controller
{
    /**
     * Show a list of filtering attributes.
     *
     * @param Request $request
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function index(Request $request)
    {
        $makeId = (int) $request->input('make') ?: null;
        $data = $this->getAttributes($makeId);

        return response()->json($data, 200);
    }

    /**
     * Get filtering attributes.
     *
     * @param int|null $makeId
     *
     * @return array
     */
    public function getAttributes($makeId)
    {
        $attributes = [
            'categories' => VehicleCategory::assigned()->lists('name', 'id'),
            'colors'     => VehicleColor::assigned()->lists('name', 'id'),
            'fuels'      => VehicleFuel::assigned()->lists('name', 'id'),
            'makes'      => VehicleMake::assigned()->lists('name', 'id'),
            'models'     => VehicleModel::assigned()->whereMakeId($makeId)->lists('name', 'id') ?: null,
            'types'      => VehicleType::assigned()->lists('name', 'id'),
        ];

        return $attributes;
    }
}

Add vehicle filtering attributes controller


<?php
namespace Joindin\Controller;

class Application extends Base
{
    protected function defineRoutes(\Slim $app)
    {
        $app->get('/', array($this, 'index'));
        $app->get('/oauth/callback', array($this, 'oauth_callback'));
    }

    public function index()
    {
        $event_collection = new \Joindin\Model\API\Event();
        $hot_events      = $event_collection->getCollection(5, 1, 'hot');
        $upcoming_events = $event_collection->getCollection(5, 1, 'upcoming');

        echo $this->application->render(
            'Application/index.html.twig',
            array(
                'hot_events'      => $hot_events,
                'upcoming_events' => $upcoming_events
            )
        );
    }

    public function oauth_callback()
    {
        $_SESSION['access_token'] = $this->application->request()->params('access_token');
        $this->application->redirect('/');
    }
}

<?php
namespace Joindin\Controller;

class Application extends Base
{
    protected function defineRoutes(\Slim $app)
    {
        $app->get('/', array($this, 'index'));
        $app->get('/oauth/callback', array($this, 'oauth_callback'));
    }

    public function index()
    {
        $event_collection = new \Joindin\Model\API\Event();
        $hot_events      = $event_collection->getCollection(5, 1, 'hot');
        $upcoming_events = $event_collection->getCollection(5, 1, 'upcoming');

        try {
            echo $this->application->render(
                'Application/index.html.twig',
                array(
                    'hot_events'      => $hot_events,
                    'upcoming_events' => $upcoming_events
                )
            );
        } catch (\Twig_Error_Runtime $e) {
            $this->application->render('Error/app_load_error.html.twig',
                array(
                    'env' => $this->application->getMode(),
                    'message' => sprintf('An exception has been thrown during the rendering of a template ("%s").', $e->getMessage()), -1, null, $e)
            );
        }
    }

    public function oauth_callback()
    {
        $_SESSION['access_token'] = $this->application->request()->params('access_token');
        $this->application->redirect('/');
    }
}

Add try/catch block to intercept problem on application load and display user friendly message, depending on application mode


<?php

namespace Sody\Exception;

use Exception;

/**
 * NoRouteFoundException
 *
 * @author Kenny Damgren <kennydamgren@gmail.com>
 * @package Sody
 */
class NoRouteFoundException extends Exception
{

}

Add new exception for routes

Add new exception for routes


<?php
namespace Oro\Component\Messaging\ZeroConfig\ConsumptionExtension;

use Oro\Component\Messaging\Consumption\Context;
use Oro\Component\Messaging\Consumption\Extension;
use Oro\Component\Messaging\Consumption\ExtensionTrait;
use Oro\Component\Messaging\ZeroConfig\Session;

class CreateQueueExtension implements Extension
{
    use ExtensionTrait;

    /**
     * @var Session
     */
    private $session;

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

    /**
     * @param Context $context
     */
    public function onStart(Context $context)
    {
        $queueName = $context->getMessageConsumer()->getQueue()->getQueueName();

        $this->session->createQueue($queueName);
    }
}

BAP-10390: Add logic witch configure broker to producer

- add extension to create queue on consumer start.


<?php

$composer = json_decode(file_get_contents(__DIR__ . '/../composer.json'), true);
$provideJson = <<<JSON
{
    "bower-asset/jquery.inputmask": "3.2.2",
    "bower-asset/jquery": "2.1.0",
    "bower-asset/punycode": "1.3.0",
    "bower-asset/yii2-pjax": "2.0.1"
}
JSON;
$provide = json_decode($provideJson, true);
$composer['provide'] = $provide;
file_put_contents(__DIR__ . '/../composer.json', json_encode($composer, JSON_PRETTY_PRINT));

Add php script to update composer.json

Add php script to update composer.json


<?php
if (!class_exists('UploadBehavior')) {
	App::import('Behavior', 'Upload.Upload');
}
class FileImportBehavior extends UploadBehavior {

	function handleUploadedFile($modelAlias, $field, $tmp, $filePath) {
			return !rename($tmp, $filePath);
	}
}
?>

Add new behavior to bypass the is_uploaded_file check.

This is useful in importing from a directory already on the filesystem.


<?php

namespace Vmwarephp\Factory;

class Service {

	static function make(\Vmwarephp\Vhost $vhost) {
		return new \Vmwarephp\Service($vhost);
	}

	static function makeConnected(\Vmwarephp\Vhost $vhost) {
		$service = self::make($vhost);
		$service->connect();
		return $service;
	}
}

Introduce vmware service factory for building services


<?php

namespace Benrowe\Laravel\Config\Facades;

use Illuminate\Support\Facades\Facade;

class Config extends Facade
{
    protected static function getFacadeAccessor()
    {

    }
}

Build basic implementation of Facade

Build basic implementation of Facade


<?php

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

class FixStatisticForeign extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		// Deletes all statistics when the game is destroyed
		Schema::table('statistics', function($table)
		{
			$table->dropForeign('statistics_game_id_foreign');
			$table->foreign('game_id')
				->references('id')
				->on('games')
				->onDelete('cascade');
		});
	}

	/**
	 * Reverse the migrations.
	 *
	 * @return void
	 */
	public function down()
	{
		// Restore previous foreign key
		Schema::table('statistics', function($table)
		{
			$table->dropForeign('statistics_game_id_foreign');
			$table->foreign('game_id')
				->references('id')
				->on('games');
		});
	}

}

Fix deleting game when statistics exist.


<?php

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

class AlterLeadAddFieldCityStreetZipcode extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('lead', function (Blueprint $table) {
            $table->string('city', 50)->nullable()->after('country_id');
            $table->string('street', 80)->nullable()->after('city');
            $table->string('zipcode', 10)->nullable()->after('street');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('lead', function (Blueprint $table) {
            $table->dropColumn('city');
            $table->dropColumn('street');
            $table->dropColumn('zipcode');
        });
    }
}

Add missing address fields for lead

Add missing address fields for lead


<?php

namespace Ilios\Migrations;

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

/**
 * Default initial school configuration sets:
 * showSessionSupplemental: true
 * showSessionSpecialAttireRequired: true
 * showSessionSpecialEquipmentRequired: true
 * showSessionAttendanceRequired: false
 *
 * Which mirrors what the setup looked like before these were configurable options
 */
class Version20170313230000 extends AbstractMigration
{
    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $sql = 'SELECT school_id FROM school WHERE school_id NOT IN (SELECT school_id from school_config)';
        $rows = $this->connection->executeQuery($sql)->fetchAll();
        if (count($rows)) {
            $insertSql = 'INSERT INTO school_config (school_id, name, value) VALUES ';
            $inserts = [];
            foreach ($rows as $arr) {
                $schoolId = $arr['school_id'];
                $inserts[] = "({$schoolId}, 'showSessionSupplemental', 'true')";
                $inserts[] = "({$schoolId}, 'showSessionSpecialAttireRequired', 'true')";
                $inserts[] = "({$schoolId}, 'showSessionSpecialEquipmentRequired', 'true')";
                $inserts[] = "({$schoolId}, 'showSessionAttendanceRequired', 'false')";
            }
            $insertSql .= implode(',', $inserts);
            unset($rows);
            unset($inserts);
        }

        if (isset($insertSql)) {
            $this->addSql($insertSql);
        }
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        $this->abortIf($this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.');
    }
}

Add default values to school configuration

So we don't have to do a dance of default values on the frontend lets
just migrate them to where they belong.


<?php

namespace Villermen\Soundboard;

use Villermen\Soundboard\App;

class Router
{
	private $app;
	private $config;
	private $routes;

	public function __construct(App $app)
	{
		$this->app = $app;
		$this->config = $app->getConfig('router');

		$this->configureRoutes();
	}

	public function configureRoutes()
	{
		foreach($this->config['routes'] as $name => $route)
		{
			$controller = new $route['controller'];

			//todo: account for methods
			$this->app->get($route['path'], [ $controller, $route['action'] ]);
		}
	}
}

<?php

namespace Villermen\Soundboard;

use Villermen\Soundboard\App;

class Router
{
	private $app;
	private $config;
	private $routes;

	public function __construct(App $app)
	{
		$this->app = $app;
		$this->config = $app->getConfig('router');

		$this->configureRoutes();
	}

	public function configureRoutes()
	{
		foreach($this->config['routes'] as $name => $route)
		{
			$controller = new $route['controller'];

			//todo: account for methods
			$this->app->map($route['methods'], $route['path'], [ $controller, $route['action'] ]);
		}
	}
}

Implement multiple http option capability


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use SimpleBrowser;

class MiNubeController extends Controller
{
    //
    private $browser;

    public function __construct()
    {
        $this->browser = new SimpleBrowser();
    }

    public function getTownByName($name){
        $query = $this->browser->get(
            'http://papi.minube.com/cities',
            [
                'lang' => 'es',
                'country_id' => 63,
                'filter' => $name,
                'api_key' => env('MINUBE_APIKEY')
            ]
        );

        $data = json_decode($query, true);

        return ($data) ? array_first($data) : [];
    }

    public function getInterestPointsByTownId($townId){
        $query = $this->browser->get(
            'http://papi.minube.com/pois',
            [
                'lang' => 'es',
                'city_id' => $townId,
                'api_key' => env('MINUBE_APIKEY')
            ]
        );

        return json_decode($query, true) ?: [];
    }
}

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use SimpleBrowser;

class MiNubeController extends Controller
{
    //
    private $browser;

    public function __construct()
    {
        $this->browser = new SimpleBrowser();
    }

    public function getTownByName($name){
        $query = $this->browser->get(
            'http://papi.minube.com/cities',
            [
                'lang' => 'es',
                'country_id' => 63,
                'filter' => $name,
                'api_key' => env('MINUBE_APIKEY')
            ]
        );

        $data = json_decode($query, true);

        return ($data) ? array_first($data) : [];
    }

    public function getInterestPointsByTownId($townId){
        $query = $this->browser->get(
            'http://papi.minube.com/pois',
            [
                'lang' => 'es',
                'city_id' => $townId,
                'api_key' => env('MINUBE_APIKEY')
            ]
        );

        return array_map(function($value){
            $value['picture_url'] = ($value['picture_url']) ? $value['picture_url'] : "default";
            return $value;
        }, json_decode($query, true)) ?: [];
    }
}

Return default value on picture_url on pois minube


<?php
namespace Bitrix24\Sonet;
use Bitrix24\Bitrix24Entity;

class SonetGroup extends  Bitrix24Entity
{
	/**
	 * @param $ORDER
	 * @param $FILTER
	 * @return array
	 */
	public function Get($ORDER, $FILTER)
	{
		/**
		 * @todo add a full result return support
		 */
		$result= $this->client->call('sonet_group.get',
			array(
				'ORDER' => $ORDER,
				'FILTER'=> $FILTER,
			));
		return $result;
	}
}

Add a sonet group class

Add a sonet group class


<?php

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

class ModifyUsersTableAddLangColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('lang')->default('en')->after('role_id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('lang');
        });
    }
}

Add lang column to users table

Add lang column to users table


<?php

use Ob_Ivan\Cache\Driver\MemoryDriver;

class MemoryDriverTest extends PHPUnit_Framework_TestCase
{
    protected $driver;

    public function setUp()
    {
        $this->driver = new MemoryDriver();
    }

    // public : tests //

    public function testDelete()
    {
        $this->assertTrue(
            $this->driver->delete(__METHOD__),
            'delete() did not return success code'
        );
    }

    public function testGet()
    {
        $this->assertNull(
            $this->driver->get(__METHOD__),
            'get() did not return null on the first call'
        );
    }

    public function testSet()
    {
        $this->assertTrue(
            $this->driver->set(__METHOD__, __METHOD__),
            'set() without duration did not return success code'
        );
        $this->assertTrue(
            $this->driver->set(__METHOD__, __METHOD__, 1),
            'set() with positive duration did not return success code'
        );
        $this->assertFalse(
            $this->driver->set(__METHOD__, __METHOD__, -1),
            'set() with negative duration did not return fail code'
        );
    }

    public function testSetGet()
    {
        $this->driver->set(__METHOD__, __METHOD__);
        $this->assertEquals(
            __METHOD__,
            $this->driver->get(__METHOD__),
            'get() did not return the value, that was previously set()'
        );
    }

    public function testSetDeleteGet()
    {
        $this->driver->set(__METHOD__, __METHOD__);
        $this->driver->delete(__METHOD__);
        $this->assertNull(
            $this->driver->get(__METHOD__),
            'get() did not return the value, that was previously delete()d'
        );
    }
}

Add simple unit test for memory cache driver


<?php
use Migrations\AbstractMigration;

class SetNotNullForCreatedTranslations extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-change-method
     * @return void
     */
    public function change()
    {
        $table = $this->table('translations');
        $table->changeColumn('created', 'datetime', [
            'default' => null,
            'null' => true
        ]);
        $table->changeColumn('modified', 'datetime', [
            'default' => null,
            'null' => true
        ]);
        $table->save();
    }
}

Set created and modified to allow null

Set created and modified to allow null


<?php
/**
 * This file is part of the PositibeLabs Projects.
 *
 * (c) Pedro Carlos Abreu <pcabreus@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Positibe\Bundle\CmfBundle\Repository;

use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
use Gedmo\Translatable\TranslatableListener;
use Symfony\Component\HttpFoundation\RequestStack;

/***
 * Class LocaleRepositoryTrait
 * @package Positibe\Bundle\CmfBundle\Repository
 *
 * @author Pedro Carlos Abreu <pcabreus@gmail.com>
 */
trait LocaleRepositoryTrait
{
    private $locale;

    /**
     * @param mixed $locale
     */
    public function setLocale($locale)
    {
        $this->locale = $locale;
    }

    public function setRequestStack(RequestStack $requestStack)
    {
        $this->locale = $requestStack->getMasterRequest()->getLocale();
    }

    public function getQuery(QueryBuilder $qb)
    {
        $query = $qb->getQuery();
        $query->setHint(
          Query::HINT_CUSTOM_OUTPUT_WALKER,
          'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker'
        );
        if ($this->locale) {
            $query->setHint(
              TranslatableListener::HINT_TRANSLATABLE_LOCALE,
              $this->locale // take locale from session or request etc.
            );

            $query->setHint(
              TranslatableListener::HINT_FALLBACK,
              1 // fallback to default values in case if record is not translated
            );
        }

        return $query;
    }
}

Move the locale repository trait to Cmf bundle, to the same 0.4.1.0


<?php

namespace ForkCMS\Core\Domain\Router;

use RuntimeException;
use Symfony\Component\Config\FileLocatorInterface;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\Config\Loader\LoaderResolverInterface;
use Symfony\Component\Routing\Loader\YamlFileLoader;
use Symfony\Component\Routing\RouteCollection;

abstract class ModuleRouteLoader extends YamlFileLoader
{
    private bool $isLoaded = false;

    final public function __construct(FileLocatorInterface $locator, string $env = null)
    {
        parent::__construct($locator, $env);
    }

    /** @return string[] */
    abstract protected function getRouterFilePaths(): array;

    final public function load($file, string $type = null): RouteCollection
    {
        if (true === $this->isLoaded) {
            throw new RuntimeException('Do not add the ' . static::class . ' loader twice');
        }

        $routes = new RouteCollection();

        foreach ($this->getRouterFilePaths() as $routerFilePath) {
            $routes->addCollection(parent::load($routerFilePath, $type));
        }

        $this->isLoaded = true;

        return $routes;
    }

    final public function supports($resource, string $type = null): bool
    {
        return 'fork' === $type;
    }

    final public function setCurrentDir(string $dir)
    {
        parent::setCurrentDir($dir);
    }

    final public function getLocator()
    {
        return parent::getLocator();
    }

    final public function import(
        $resource,
        string $type = null,
        bool $ignoreErrors = false,
        string $sourceResource = null,
        $exclude = null
    ) {
        return parent::import(
            $resource,
            $type,
            $ignoreErrors,
            $sourceResource,
            $exclude
        );
    }

    final protected function glob(
        string $pattern,
        bool $recursive,
        &$resource = null,
        bool $ignoreErrors = false,
        bool $forExclusion = false,
        array $excluded = []
    ) {
        return parent::glob(
            $pattern,
            $recursive,
            $resource,
            $ignoreErrors,
            $forExclusion,
            $excluded
        );
    }

    final public function getResolver(): LoaderResolverInterface
    {
        return parent::getResolver();
    }

    final public function setResolver(LoaderResolverInterface $resolver): void
    {
        parent::setResolver($resolver);
    }

    final public function resolve($resource, string $type = null): static|LoaderInterface
    {
        return parent::resolve($resource, $type);
    }

    final protected function parseRoute(RouteCollection $collection, string $name, array $config, string $path): void
    {
        parent::parseRoute($collection, $name, $config, $path);
    }

    final protected function parseImport(RouteCollection $collection, array $config, string $path, string $file): void
    {
        parent::parseImport($collection, $config, $path, $file);
    }

    final protected function validate($config, string $name, string $path): void
    {
        parent::validate($config, $name, $path);
    }
}

Add dynamic module route loader

Add dynamic module route loader


<?PHP
	$g_link = false;
	if(is_resource($g_link)  &&  get_resource_type($g_link)=='mysql link'){
	   echo 'MYSQL';
	}else{
		if(is_object($g_link)  && get_class($g_link)=='mysqli'){
			echo 'MYSQLI';
		}
	}
?>

Check if database is MySQL or MySQLi

Check if database is MySQL or MySQLi


<?php
// Comparison function
function cmp($a, $b) {
    if ($a == $b) {
        return 0;
    }
    return ($a < $b) ? -1 : 1;
}

// Array to be sorted
$array = array('a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4);
print_r($array);

// Sort and print the resulting array
uasort($array, 'cmp');
print_r($array);
?>

Sort an array with a user-defined comparison function and maintain index association


<?php

namespace App\Console\Commands;

use App\Notifications\DearSanta as DearSantaNotification;
use App\Models\DearSanta;
use DrawCrypt;
use Illuminate\Console\Command;

class SendDearSanta extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'send:dearSanta {dearSanta : ID of the dearsanta} {iv : The decryption iv}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send again an email to a santa';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $iv = base64_decode($this->argument('iv'));
        DrawCrypt::setIV($iv);

        $dearSanta = DearSanta::find($this->argument('dearSanta'));

        $dearSanta->sender->santa->notify(new DearSantaNotification($dearSanta));
        $this->info('DearSanta mail sent');
    }
}

Add command to resend DearSanta email

Add command to resend DearSanta email


<?php
namespace TYPO3\Flow\Persistence\Doctrine\Migrations;

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

/**
 * Auto-generated Migration: Please modify to your needs! This block will be used as the migration description if getDescription() is not used.
 */
class Version20160530132725 extends AbstractMigration
{

    /**
     * @return string
     */
    public function getDescription() {
        return '';
    }

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

        $this->addSql('ALTER TABLE sandstorm_usermanagement_domain_model_registrationflow ADD firstname VARCHAR(255) DEFAULT NULL, ADD lastname VARCHAR(255) DEFAULT NULL');
    }

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

        $this->addSql('ALTER TABLE sandstorm_usermanagement_domain_model_registrationflow DROP firstname, lastname');
    }
}

Add migration for registration flow

TASK: Add migration for registration flow


<?php

/**
 * Created by PhpStorm.
 * User: anton
 * Date: 10.10.16
 * Time: 15:51
 */
class Dict extends Zend_Db_Table_Row
{
    protected $_tableClass = 'Dicts';

    public function delete()
    {
        $config = Zend_Registry::get('config');
        unlink("{$config->paths->storage->dicts}/{$this->hash}.dict");
        return parent::delete();
    }
}

Delete dict file when dict db-record delete


<?php

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

class CreateVersionControlSystemsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('version_control_systems', function (Blueprint $table) {
            $table->increments('id');
            $table->string('user_agent')->index();
            $table->string('name');
            $table->timestamps();
        });
    }

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

Add version control system migration

Add version control system migration


<?php

class ParserTests extends \phpunit\framework\TestCase
{
    public function testInitBasicMarkdownParser()
    {
        $parser = new \Mybb\Parser\Parser(new \s9e\TextFormatter\Configurator(), [
            'formatter_type' => 'markdown',
        ]);

        $markdown = <<<EOT
# This is a simple test

* This is a list.
* It's only two items long.
EOT;

        $expected = <<<EOT

This is a simple test

This is a list.

It's only two items long.

EOT;

        $actual = $parser->parse($markdown);

        $this->assertEquals($expected, $actual);
    }
}

<?php

class ParserTests extends PHPUnit_Framework_TestCase
{
    public function testInitBasicMarkdownParser()
    {
        $parser = new \Mybb\Parser\Parser(new \s9e\TextFormatter\Configurator(), [
            'formatter_type' => 'markdown',
        ]);

        $markdown = <<<EOT
# This is a simple test

* This is a list.
* It's only two items long.
EOT;

        $expected = <<<EOT

This is a simple test

This is a list.

It's only two items long.

EOT;

        $actual = $parser->parse($markdown);

        $this->assertEquals($expected, $actual);
    }
}

Fix unit test for older version of phpunit.


<?php

/** @var Mage_Core_Model_Resource_Setup $installer */
$installer = $this;
$installer->startSetup();

$tableName = Mage::getSingleton('core/resource')->getTableName('algoliasearch/queue');

$installer->run('ALTER TABLE ' . $tableName . ' MODIFY data TEXT NOT NULL');

$installer->endSetup();

Change algolia queue data column type to TEXT


<?php
/**
 * Template Name: Journal Template
 */
?>

<?php get_template_part('templates/page', 'header'); ?>

Hi

<?php if (!have_posts()) : ?>

    <?php _e('Sorry, no results were found.', 'sage'); ?>

  <?php get_search_form(); ?>
<?php endif; ?>
<?php
$args = array( 'post_type' => 'post', 'posts_per_page' => 10 );
$zoo_loop = new WP_Query( $args );
?>

<?php while ($zoo_loop->have_posts()) : $zoo_loop->the_post(); ?>
  <?php get_template_part('templates/content', get_post_type() != 'post' ? get_post_type() : get_post_format()); ?>
  <?php echo get_post_type() ?>
<?php endwhile; ?>

<?php the_posts_navigation(); ?>

Move journal tamplate file here.

Move journal tamplate file here.


<?php

namespace App\Http\Controllers\User;

use App\User;
use App\Authorized;
use phpseclib\Crypt\RSA;
use Illuminate\Http\Request;
use App\Exception\RSAException;
use PragmaRX\Google2FA\Google2FA;
use App\Http\Controllers\Controller;

class AuthorController extends Controller
{
    public function showAuthorPage(){
        return view('user.author');
    }

    public function handleAuthorization(Request $request){
        $this->validate($request, [
            'student_id' => 'required|integer|digits:5',
        ]);
    }

    public function validateGoogle2FA(Request $request){
        $google2fa = new Google2FA();

        if($google2fa->verifyKey($user->google2fa_secret, $request->input('2fa'))){
            $token = bin2hex(openssl_random_pseudo_bytes(16));
            Session::flash('author_key', $token);

            return response()->json([
                'status' => 'ok',
                'token' => $token,
            ], 200);
        }else{
            return response()->json([
                'status' => 'Invalid 2 factor token'
            ], 401);
        }
    }

    private function verifyValidCommand(){

    }

    private function getRSAKey(){
        $key['publickey'] = User::where('username', Session::get('username'))->pluck('rsa_key.public_key')[0];
        $key['privatekey'] = User::where('username', Session::get('username'))->pluck('rsa_key.private_key')[0];

        // TODO : Decrypt the keys (Since these keys will be encrypted)

        return $key;
    }

    private function signCheckOutRequest($message){
        $rsa = new RSA;
        $key = $this->getRSAKey();

        if(!$rsa->loadkey($key['privatekey']) || !$rsa->loadkey($key['publickey'])){
            throw new RSAException('Cannot load keypair');
        }

        if(!$rsa->sign($message)){
            throw new RSAException('Cannot sign message');
        }else{
            return $rsa->sign($message);
        }
    }

    private function authorizeCheckOut(Request $request){
        Authorized::insert([
            'student_id' => $request->input('student_id'),
            'signature' => 'sign',
        ]);
    }

    private function validateCheckOutRequest(){
        return;
    }
}

[W.I.P] Create controller to handle authorization for student to leave


<?php

Autoloader::namespaces(array(
	'fluxbb' => __DIR__ . DS . 'models',
));

Autoloader::underscored(array(
	'FluxBB' => __DIR__ . DS . 'classes',
));

Create a basic "bundle" called fluxbb/core.


<?php namespace Aedart\Scaffold\Tasks;

use Aedart\Scaffold\Containers\IoC;
use Aedart\Scaffold\Contracts\Collections\Templates;
use Aedart\Scaffold\Handlers\Utility\PropertyHandlerResolver;

/**
 * Ask For Template Destination
 *
 * @author Alin Eugen Deac <aedart@gmail.com>
 * @package Aedart\Scaffold\Tasks
 */
class AskForTemplateDestination extends BaseTask
{
    use PropertyHandlerResolver;

    protected $description = 'Processes destination properties for template(s)';

    /**
     * Performs the actual task execution
     *
     * @return void
     */
    public function performTask()
    {
        // Check if there are any templates, which might need destinations...
        $templateKey = 'templates';
        if(!$this->config->has($templateKey) || count($this->config->get($templateKey, [])) == 0){
            $this->output->note('No templates to process');
            return;
        }

        // Get the templates collection
        $collection = $this->parseTemplatesCollection($this->config->get($templateKey));

        // Process the "destination" properties for each template
        foreach($collection->all() as $id => $template){
            // Get the destination property
            $property = $template->getDestination();

            // Set the property's id!
            $property->setId($id);

            // Create the key, where the processed value
            // will be stored (inside the configuration).
            $key = $templateKey . '.' . $id . '.destination.value';

            // Get the handler
            $handler = $this->makePropertyHandler($key);

            // Process the property
            $handler->processProperty($property);
        }
    }

    /**
     * Parse the given properties list and return a collection
     *
     * @param array $templates
     *
     * @return Templates
     */
    protected function parseTemplatesCollection(array $templates = [])
    {
        $ioc = IoC::getInstance();

        return $ioc->make(Templates::class, $templates);
    }
}

Add task that asks for template destinations

Basically this task reuses the property handler to obtain information
about where a given template's destination must be.


@extends('layouts.app')
@section('content')

Page not found

The request page was not found here.

@endsection

Add HTTP 404 error page

Add HTTP 404 error page


<?php
namespace Base;
define('PNG_ASSET_DIR', SP . 'assets/images/');
class PngAssetView extends AssetView {
  public static $directory = PNG_ASSET_DIR;

  public static $ext = '.png';
  public static $mime = 'image/png';

}

Add a PNG asset view

Add a PNG asset view


<?php
namespace spec\Nats;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class ConnectionSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('Nats\Connection');
    }

    function it_has_ping_count_to_zero()
    {
        $this->pingsCount()->shouldBe(0);
    }

    function it_has_pubs_count_to_zero()
    {
        $this->pubsCount()->shouldBe(0);
    }

    function it_has_reconnects_count_to_zero()
    {
        $this->reconnectsCount()->shouldBe(0);
    }

    function it_has_subscriptions_count_to_zero()
    {
        $this->subscriptionsCount()->shouldBe(0);
    }

    function it_subscriptions_array_is_empty()
    {
        $this->getSubscriptions()->shouldHaveCount(0);
    }
}

Check default vaules of connection

Check default vaules of connection


<?php

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

class ContestVotesChangeWeightingToFloat extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('contest_votes', function (Blueprint $table) {
            $table->float('weight')->default(1.0)->change();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('contest_votes', function (Blueprint $table) {
            $table->tinyInteger('weight')->default(1)->change();
        });
    }
}

Change weight on contest_votes to a float


<?php

/**
 * This test class pretends to be an RSS aggregator. It logs notifications
 * from the cloud.
 *
 * PHP version 5
 *
 * @category Plugin
 * @package  StatusNet
 * @author   Zach Copley <zach@status.net>
 * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
 * @link     http://status.net/
 *
 * StatusNet - the distributed open-source microblogging tool
 * Copyright (C) 2009, StatusNet, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

if (!defined('STATUSNET')) {
    exit(1);
}

class LoggingAggregatorAction extends Action
{

    /**
     * Initialization.
     *
     * @param array $args Web and URL arguments
     *
     * @return boolean false if user doesn't exist
     */
    function prepare($args)
    {
        parent::prepare($args);
        return true;
    }

    function handle($args)
    {
        parent::handle($args);

        if ($_SERVER['REQUEST_METHOD'] != 'POST') {
			$this->showError('This resource requires an HTTP POST.');
        }

        $this->url = $this->arg('url');

        if (empty($this->url)) {
            $this->showError('Hey, you have to provide a url parameter.');
        }

        $this->ip  = $_SERVER['REMOTE_ADDR'];

        common_log(LOG_INFO, 'RSSCloud Logging Aggregator - ' . $this->ip . ' claims the feed at ' .
                   $this->url . ' has been updated.');

        header('Content-Type: text/xml');
        echo '<notifyResult success=\'true\' msg=\'Thanks for the update.\' />' . "\n";

	}

    function showError($msg)
    {
        header('HTTP/1.1 403 Forbidden');
        header('Content-Type: text/xml');
        echo "<?xml version='1.0'?>\n";
        echo "<notifyResult success='false' msg='$msg' />\n";
        exit();
    }

}

Test action to simulate an aggregator. Useful for checking that the cloud hub is sending notifications.


<?php

/**
 * Represents the WordPress option for saving the dismissed messages.
 */
class Whip_WPDismissOption implements Whip_DissmisStorage {

	/**
	 * Saves the value to the options.
	 *
	 * @param array $dismissed The value to save.
	 */
	public function save( array $dismissed ) {
		update_option( 'whip_dismissed', $dismissed );
	}

	/**
	 * Returns the value of the whip_dismissed option.
	 *
	 * @return array
	 */
	public function get() {
		$dismissedOption = maybe_unserialize( get_option( 'whip_dismissed' ) );
		if ( ! $dismissedOption ) {
			return array() ;
		}

		return $dismissedOption;
	}

}

Add class for the wordpress dismiss option.


<?php
/**
 * @todo <Test description here>
 * @file      GetClassName.php
 *
 * PHP version 5.4+
 *
 * @author    Yancharuk Alexander <alex at itvault dot info>
 * @copyright © 2013-2016 Yancharuk Alexander
 * @date      Thu Dec 01 18:42:13 2016
 * @license   The BSD 3-Clause License.
 *            <https://tldrlegal.com/license/bsd-3-clause-license-(revised)>
 */

namespace Tests;

use Veles\Tools\CliProgressBar;
use Veles\Tools\Timer;
use Application\TestApplication;

/**
 * Class GetClassName
 *
 * @author Yancharuk Alexander <alex at itvault dot info>
 */
class GetClassName extends TestApplication
{
    protected $repeats = 10000;

	public function run()
	{
		$repeats = $this->getRepeats();

		Timer::reset();
		$bar = new CliProgressBar($repeats);
		for ($i = 1; $i <= $repeats; ++$i) {
			Timer::start();
			get_class($this);
			Timer::stop();
			$bar->update($i);
		}

		$this->addResult('get_class', Timer::get());

		Timer::reset();
		$bar = new CliProgressBar($repeats);
		for ($i = 1; $i <= $repeats; ++$i) {
			Timer::start();
			self::class;
			Timer::stop();
			$bar->update($i);
		}

		$this->addResult('self::class', Timer::get());

		Timer::reset();
		$bar = new CliProgressBar($repeats);
		for ($i = 1; $i <= $repeats; ++$i) {
			Timer::start();
			GetClassName::class;
			Timer::stop();
			$bar->update($i);
		}

		$this->addResult('Class::class', Timer::get());
	}
}

Test for receiving class name algos

Test for receiving class name algos


<?php

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

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

class AlterJobsDropReserved extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('jobs', function (Blueprint $table) {
            $table->dropColumn('reserved');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('jobs', function (Blueprint $table) {
            $table->tinyInteger('reserved')->unsigned()->after('attempts');
        });
    }
}

Remove unused "reserved" column from jobs table


<?php

/**
 * This file is part of the ValueObjects package.
 *
 * (c) Lorenzo Marzullo <marzullo.lorenzo@gmail.com>
 */

namespace ValueObjects\Enum;

use MyCLabs\Enum\Enum;
use ValueObjects\ValueObjectInterface;

/**
 * Class AbstractEnum.
 *
 * @package ValueObjects
 * @author  Lorenzo Marzullo <marzullo.lorenzo@gmail.com>
 * @link    http://github.com/lorenzomar/valueobjects
 */
abstract class AbstractEnum extends Enum implements ValueObjectInterface
{
    public function sameValueAs(ValueObjectInterface $valueObject)
    {
        return $this == $valueObject;
    }

    public function copy()
    {
        return clone $this;
    }

    public function __clone()
    {
        return new static($this->getValue());
    }
}

Add enum type value object

Add enum type value object


<?php namespace ProcessWire\GraphQL\Test\Permissions;

use ProcessWire\GraphQL\Test\GraphqlTestCase;
use ProcessWire\GraphQL\Utils;

class SuperuserCreateNotAllowedTemplateParentTemplatesTest extends GraphqlTestCase {

  /**
   * + The target template is legal.
   * + The target parent template is legal.
   * + The target parent can have any child.
   * - The target template has parentTemplates without target parent.
   */
  public static function getSettings()
  {
    return [
      'login' => 'admin',
      'legalTemplates' => ['city', 'skyscraper'],
      'legalFields' => ['title'],
    ];
  }

  public function testPermission() {
    $architects = Utils::pages()->get("template=architects");
    $query = 'mutation createPage($page: SkyscraperCreateInput!) {
      createSkyscraper(page: $page) {
        id
        name
        title
        template
      }
    }';

    $variables = [
      'page' => [
        'parent' => $architects->id,
        'name' => 'search-2',
        'title' => 'Search 2'
      ]
    ];

    $res = self::execute($query, $variables);
    $this->assertEquals(1, count($res->errors), 'Should not allow to create a page under the page with template that is not in parentTemplates of the target template.');
    $this->assertStringContainsString('parent', $res->errors[0]->message);
  }
}

Add create permission test for Superuser.


<?php
/**
 * This file is part of the Zimbra API in PHP library.
 *
 * © Nguyen Van Nguyen <nguyennv1981@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Zimbra\Voice\Request;

use Zimbra\Soap\Request;

/**
 * Base voice request class
 *
 * @package    Zimbra
 * @subpackage Voice
 * @category   Request
 * @author     Nguyen Van Nguyen - nguyennv1981@gmail.com
 * @copyright  Copyright © 2013 by Nguyen Van Nguyen.
 */
abstract class Base extends Request
{
    /**
     * Constructor method for base request
     * @param  string $value
     * @return self
     */
    public function __construct($value = null)
    {
        parent::__construct($value);
        $this->requestNamespace('urn:zimbraVoice');
    }
}

Initialize Voice base request class

Initialize Voice base request class


<?php

namespace Doctrine\Tests\ORM\Functional\Ticket;

use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types as DBALTypes;

class DDC5684Test extends \Doctrine\Tests\OrmFunctionalTestCase
{
    protected function setUp()
    {
        parent::setUp();

        if (DBALTypes\Type::hasType(DDC5684ObjectIdType::NAME)) {
            DBALTypes\Type::overrideType(DDC5684ObjectIdType::NAME, DDC5684ObjectIdType::CLASSNAME);
        } else {
            DBALTypes\Type::addType(DDC5684ObjectIdType::NAME, DDC5684ObjectIdType::CLASSNAME);
        }

        $this->_schemaTool->createSchema([$this->_em->getClassMetadata(DDC5684Object::CLASSNAME)]);
    }

    protected function tearDown()
    {
        $this->_schemaTool->dropSchema([$this->_em->getClassMetadata(DDC5684Object::CLASSNAME)]);

        parent::tearDown();
    }

    public function testAutoIncrementIdWithCustomType()
    {
        $object = new DDC5684Object();
        $this->_em->persist($object);
        $this->_em->flush();

        $this->assertInstanceOf(DDC5684ObjectId::CLASSNAME, $object->id);
    }

    public function testFetchObjectWithAutoIncrementedCustomType()
    {
        $object = new DDC5684Object();
        $this->_em->persist($object);
        $this->_em->flush();
        $this->_em->clear();

        $rawId = $object->id->value;
        $object = $this->_em->find(DDC5684Object::CLASSNAME, new DDC5684ObjectId($rawId));

        $this->assertInstanceOf(DDC5684ObjectId::CLASSNAME, $object->id);
        $this->assertEquals($rawId, $object->id->value);
    }
}

class DDC5684ObjectIdType extends DBALTypes\IntegerType
{
    const NAME      = 'ticket_5684_object_id';
    const CLASSNAME = __CLASS__;

    public function convertToPHPValue($value, AbstractPlatform $platform)
    {
        return new DDC5684ObjectId($value);
    }

    public function convertToDatabaseValue($value, AbstractPlatform $platform)
    {
        return $value->value;
    }

    public function getName()
    {
        return self::NAME;
    }

    public function requiresSQLCommentHint(AbstractPlatform $platform)
    {
        return true;
    }
}

class DDC5684ObjectId
{
    const CLASSNAME = __CLASS__;

    public $value;

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

    public function __toString()
    {
        return (string) $this->value;
    }
}

/**
 * @Entity
 * @Table(name="ticket_5684_objects")
 */
class DDC5684Object
{
    const CLASSNAME = __CLASS__;

    /**
     * @Id
     * @Column(type="ticket_5684_object_id")
     * @GeneratedValue(strategy="AUTO")
     */
    public $id;
}

Add test case for autoincremented id of custom type