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

/**
 * Created by Liming
 * Date: 2016/11/4
 * Time: 16:10
 */

namespace Judge;

class CppJudge extends Judger {
    protected $filename = 'main.cpp';

    /**
     * 测试命令行
     * @return string
     */
    protected function command() {
        return sprintf(
            'docker run -v %s:/mnt/main.cpp:ro -i --rm --net none liming/cpp -t %d -m %d < %s 2>/dev/null',
            $this->filename,
            $this->time_limit,
            $this->memory_limit,
            $this->test_case
        );
    }
}

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

/**
 * Created by Liming
 * Date: 2016/11/4
 * Time: 16:10
 */

namespace Judge;

class CppJudge extends Judger {
    protected $filename = 'main.cpp';

    /**
     * 测试命令行
     * @return string
     */
    protected function command() {
        return sprintf(
            'docker run -v %s:/mnt/main.cpp:ro -i --rm --net none --security-opt seccomp=unconfined liming/cpp -t %d -m %d < %s 2>/dev/null',
            $this->filename,
            $this->time_limit,
            $this->memory_limit,
            $this->test_case
        );
    }
}

Disable seccomp in docker to use EasySandbox.😵


<?php

namespace GeneratedHydratorTest\CodeGenerator\Visitor;

use GeneratedHydrator\CodeGenerator\Visitor\MethodDisablerVisitor;
use PHPParser_Node_Name;
use PHPParser_Node_Stmt_Class;
use PHPParser_Node_Stmt_ClassMethod;
use PHPParser_Node_Stmt_Namespace;
use PHPUnit_Framework_TestCase;

/**
 * @group CodeGeneration
 */
class MethodDisablerVisitorTest extends PHPUnit_Framework_TestCase
{
    public function testDisablesMethodWhenFiltering()
    {
        $visitor = new MethodDisablerVisitor(
            function () {
                return true;
            }
        );

        $method = new PHPParser_Node_Stmt_ClassMethod('test');

        $this->assertSame($method, $visitor->enterNode($method));
        $this->assertInstanceOf('PHPParser_Node_Stmt_Throw', reset($method->stmts));
    }
}

<?php

namespace GeneratedHydratorTest\CodeGenerator\Visitor;

use GeneratedHydrator\CodeGenerator\Visitor\MethodDisablerVisitor;
use PHPParser_Node_Name;
use PHPParser_Node_Stmt_Class;
use PHPParser_Node_Stmt_ClassMethod;
use PHPParser_Node_Stmt_Namespace;
use PHPUnit_Framework_TestCase;

/**
 * @group CodeGeneration
 */
class MethodDisablerVisitorTest extends PHPUnit_Framework_TestCase
{
    public function testDisablesMethod()
    {
        $method = new PHPParser_Node_Stmt_ClassMethod('test');
        $filter = $this->getMock('stdClass', array('__invoke'));

        $filter->expects($this->once())->method('__invoke')->with($method)->will($this->returnValue(true));

        $visitor = new MethodDisablerVisitor($filter);

        $this->assertSame($method, $visitor->enterNode($method));
        $this->assertInstanceOf('PHPParser_Node_Stmt_Throw', reset($method->stmts));
    }

    public function testSkipsOnFailedFiltering()
    {
        $method = new PHPParser_Node_Stmt_ClassMethod('test');
        $filter = $this->getMock('stdClass', array('__invoke'));

        $filter->expects($this->once())->method('__invoke')->with($method)->will($this->returnValue(false));

        $visitor = new MethodDisablerVisitor($filter);

        $this->assertSame(null, $visitor->enterNode($method));
    }

    public function testSkipsOnNodeTypeMismatch()
    {
        $class  = new PHPParser_Node_Stmt_Class('test');
        $filter = $this->getMock('stdClass', array('__invoke'));

        $filter->expects($this->never())->method('__invoke');

        $visitor = new MethodDisablerVisitor($filter);

        $this->assertSame(null, $visitor->enterNode($class));
    }
}

Complete coverage on the method disabler visitor


<?php

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

/**
 * sfValidatorEmail validates emails.
 *
 * @package    symfony
 * @subpackage validator
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id$
 */
class sfValidatorEmail extends sfValidatorRegex
{
  const REGEX_EMAIL = '/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i';

  /**
   * @see sfValidatorRegex
   */
  protected function configure($options = array(), $messages = array())
  {
    parent::configure($options, $messages);

    $this->setOption('pattern', self::REGEX_EMAIL);
  }
}

<?php

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

/**
 * sfValidatorEmail validates emails.
 *
 * @package    symfony
 * @subpackage validator
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id$
 */
class sfValidatorEmail extends sfValidatorRegex
{
  const REGEX_EMAIL = '/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i';

  /**
   * @see sfValidatorRegex
   */
  protected function configure($options = array(), $messages = array())
  {
    parent::configure($options, $messages);

    $this->setOption('pattern', self::REGEX_EMAIL);
    $this->addOption('check_domain', false);
  }

  protected function doClean($value)
  {
    $clean = parent::doClean($value);

    if ($this->getOption('check_domain') && function_exists('checkdnsrr'))
    {
      $tokens = explode('@', $clean);
      if (!checkdnsrr($tokens[1], 'MX') && !checkdnsrr($tokens[1], 'A'))
      {
        throw new sfValidatorError($this, 'invalid', array('value' => $clean));
      }
    }

    return $clean;
  }
}

Add support for MX validation in sfValidatorEmail


<?php

namespace ProjectRena\Task;

use Cilex\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class ResqueCron.
 */
class ResqueTask extends Command
{
				/**
				 *
				 */
				protected function configure()
				{
								$this->setName('resque:run')->setDescription('Fires up resque');
				}

				/**
				 * @param InputInterface $input
				 * @param OutputInterface $output
				 *
				 * @return int|null|void
				 */
				protected function execute(InputInterface $input, OutputInterface $output)
				{
								putenv("VERBOSE=1");
								putenv("QUEUE=now,important,default");

								include __DIR__ . "/../../vendor/chrisboulton/php-resque/resque.php";
				}
}

<?php

namespace ProjectRena\Task;

use Cilex\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class ResqueCron.
 */
class ResqueTask extends Command
{
				/**
				 *
				 */
				protected function configure()
				{
								$this->setName('resque:run')->setDescription('Fires up resque');
				}

				/**
				 * @param InputInterface $input
				 * @param OutputInterface $output
				 *
				 * @return int|null|void
				 */
				protected function execute(InputInterface $input, OutputInterface $output)
				{
								putenv("VERBOSE=0");
								include __DIR__ . "/../../vendor/chrisboulton/php-resque/resque.php";
				}
}

Remove the resque queue naming from the resque task runner, and also remove verbose


<?php

/**
 * @group conduit
 */
final class ConduitAPI_maniphest_update_Method
  extends ConduitAPI_maniphest_Method {

  public function getMethodDescription() {
    return "Update an existing Maniphest task.";
  }

  public function defineErrorTypes() {
    return array(
      'ERR-BAD-TASK'          => 'No such maniphest task exists.',
      'ERR-INVALID-PARAMETER' => 'Missing or malformed parameter.'
    );
  }

  public function defineParamTypes() {
    return $this->getTaskFields($is_new = false);
  }

  public function defineReturnType() {
    return 'nonempty dict';
  }

  protected function execute(ConduitAPIRequest $request) {
    $id = $request->getValue('id');
    $phid = $request->getValue('phid');

    if (($id && $phid) || (!$id && !$phid)) {
      throw new Exception("Specify exactly one of 'id' and 'phid'.");
    }

    if ($id) {
      $task = id(new ManiphestTask())->load($id);
    } else {
      $task = id(new ManiphestTask())->loadOneWhere(
        'phid = %s',
        $phid);
    }

    if (!$task) {
      throw new ConduitException('ERR-BAD-TASK');
    }

    $this->applyRequest($task, $request, $is_new = false);

    return $this->buildTaskInfoDictionary($task);
  }

}

<?php

/**
 * @group conduit
 */
final class ConduitAPI_maniphest_update_Method
  extends ConduitAPI_maniphest_Method {

  public function getMethodDescription() {
    return "Update an existing Maniphest task.";
  }

  public function defineErrorTypes() {
    return array(
      'ERR-BAD-TASK'          => 'No such maniphest task exists.',
      'ERR-INVALID-PARAMETER' => 'Missing or malformed parameter.',
      'ERR-NO-EFFECT'         => 'Update has no effect.',
    );
  }

  public function defineParamTypes() {
    return $this->getTaskFields($is_new = false);
  }

  public function defineReturnType() {
    return 'nonempty dict';
  }

  protected function execute(ConduitAPIRequest $request) {
    $id = $request->getValue('id');
    $phid = $request->getValue('phid');

    if (($id && $phid) || (!$id && !$phid)) {
      throw new Exception("Specify exactly one of 'id' and 'phid'.");
    }

    if ($id) {
      $task = id(new ManiphestTask())->load($id);
    } else {
      $task = id(new ManiphestTask())->loadOneWhere(
        'phid = %s',
        $phid);
    }

    $params = $request->getAllParameters();
    unset($params['id']);
    unset($params['phid']);
    $params = call_user_func_array('coalesce', $params);

    if (!$params) {
      throw new ConduitException('ERR-NO-EFFECT');
    }

    if (!$task) {
      throw new ConduitException('ERR-BAD-TASK');
    }

    $this->applyRequest($task, $request, $is_new = false);

    return $this->buildTaskInfoDictionary($task);
  }

}

Implement option 1 from T3210

Implement option 1 from T3210

Summary: Fixes T3210

Test Plan: Run the conduit call via the UI and ensure it no longer breaks. Check I get an error returned if no params are set

Reviewers: epriestley

Reviewed By: epriestley

CC: aran, Korvin

Maniphest Tasks: T3210

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


<?php
/**
 * Lizmap FTS searcher.
 *
 * @author    3liz
 * @copyright 2017 3liz
 *
 * @see      http://3liz.com
 *
 * @license    Mozilla Public License : http://www.mozilla.org/MPL/
 */
class lizmapFtsSearchListener extends jEventListener
{
    public function onsearchServiceItem($event)
    {
        // Check if needed table lizmap_fts is queryable
        if ($this->checkLizmapFts()) {
            $event->add(
                array(
                    'type' => 'Fts',
                    'service' => 'lizmapFts',
                    'url' => jUrl::get('lizmap~searchFts:get'),
                )
            );
        }
    }

    protected function checkLizmapFts()
    {
        $ok = false;
        $profile = 'search';

        try {
            // try to get the specific search profile to do not rebuild it
            jProfiles::get('jdb', $profile, true);
        } catch (Exception $e) {
            // else use default
            $profile = null;
        }

        // Try to get data from lizmap_fts table / view / materialized view
        try {
            // try to get the specific search profile to do not rebuild it
            $cnx = jDb::getConnection($profile);
            $cnx->query('SELECT * FROM lizmap_search LIMIT 0;');
            $ok = true;
        } catch (Exception $e) {
            $ok = false;
        }

        return $ok;
    }
}

<?php
/**
 * Lizmap FTS searcher.
 *
 * @author    3liz
 * @copyright 2017 3liz
 *
 * @see      http://3liz.com
 *
 * @license    Mozilla Public License : http://www.mozilla.org/MPL/
 */
class lizmapFtsSearchListener extends jEventListener
{
    public function onsearchServiceItem($event)
    {
        // Check if needed table lizmap_fts is queryable
        if ($this->checkLizmapFts()) {
            $event->add(
                array(
                    'type' => 'Fts',
                    'service' => 'lizmapFts',
                    'url' => jUrl::get('lizmap~searchFts:get'),
                )
            );
        }
    }

    protected function checkLizmapFts()
    {
        $ok = false;
        $profile = 'search';

        try {
            // try to get the specific search profile to do not rebuild it
            jProfiles::get('jdb', $profile, true);
        } catch (Exception $e) {
            // else use default
            $profile = null;
        }

        // Try to get data from lizmap_fts table / view / materialized view
        try {
            // try to get the specific search profile to do not rebuild it
            $cnx = jDb::getConnection($profile);
            @$cnx->query('SELECT * FROM lizmap_search LIMIT 0;');
            $ok = true;
        } catch (Exception $e) {
            $ok = false;
        }

        return $ok;
    }
}

Remove warning about lizmap_search Quick fix FTW!


<?php

return [
    'big' => [
        'auth_file' => env('BIG_AUTH_FILE'),
        'project_id' => env('BIG_PROJECT_ID'),
    ],
];

<?php

return [
    'big' => [
        'auth_file' => env('BIG_AUTH_FILE'),
        'project_id' => env('BIG_PROJECT_ID'),
        'default_dataset' => env('BIG_DEFAULT_DATASET'),
    ],
];

Add a default dataset option.

Add a default dataset option.


<?php

return [
    'title' => [
        'media' => 'Média',
        'edit media' => 'Edition de média',
    ],
    'breadcrumb' => [
        'media' => 'Média',
    ],
    'table' => [
        'filename' => 'Nom de fichier',
        'width' => 'Largeur',
        'height' => 'Hauteur',
    ],
    'validation' => [
        'max_size' => 'Taille maximale (:size) du dossier Media atteint.',
    ],
    'file-sizes' => [
        'B' => 'Octet',
        'KB' => 'Ko',
        'MB' => 'Mo',
        'GB' => 'Go',
        'TB' => 'To',
    ],
    'choose file' => 'Choissisez un fichier',
    'insert' => 'Sélectionner ce fichier',
    'file picker' => 'Sélectionneur de fichier',
    'Browse' => 'Parcourir ...',
];

<?php

return [
    'title' => [
        'media' => 'Média',
        'edit media' => 'Edition de média',
    ],
    'breadcrumb' => [
        'media' => 'Média',
    ],
    'table' => [
        'filename' => 'Nom de fichier',
        'width' => 'Largeur',
        'height' => 'Hauteur',
    ],
    'form' => [
        'alt_attribute' => 'Attribut alt',
        'description' => 'Description',
        'keywords' => 'Mots clés',
    ],
    'validation' => [
        'max_size' => 'Taille maximale (:size) du dossier Media atteint.',
    ],
    'file-sizes' => [
        'B' => 'Octet',
        'KB' => 'Ko',
        'MB' => 'Mo',
        'GB' => 'Go',
        'TB' => 'To',
    ],
    'choose file' => 'Choissisez un fichier',
    'insert' => 'Sélectionner ce fichier',
    'file picker' => 'Sélectionneur de fichier',
    'Browse' => 'Parcourir ...',
];

Update French Translation for Media modules


<?php
// Grab the "Global" settings from drupdates
$result = json_decode(exec('python ~/.drush/settings.py'), true);
$path = $result['workingDir']['value'];
$driver = $result['datastoreDriver']['value'];
$user = $result['datastoreSuperUser']['value'];
$pass = $result['datastoreSuperPword']['value'];
$port = $result['datastorePort']['value'];
$host = $result['datastoreHost']['value'];
$webroot = $result['webrootDir']['value'];

// I'm not sure why but if you keep $result populated you get ghost aliases who
// values are the same as the $result array elelment names
$result = array();
$aliases = array();
$dir_handle = new DirectoryIterator($path);
while($dir_handle->valid()) {
  if($dir_handle->isDir() && !$dir_handle->isDot()) {
    $basename = $dir_handle->getBasename();
    $root = $dir_handle->getPathname();
    $root = $webroot = "" ? $root : $root . $webroot;
    $aliases[$basename] = array(
      'uri' => 'http://localhost/' . $basename,
      'root' => $root,
      'databases' => array(
        'default' => array(
          'default' => array(
            'driver' => $driver,
            'username' => $user,
            'password' => $pass,
            'port' => $port,
            'host' => $host,
            'database' => $basename,
          ),
        ),
      ),
    );
  }
  $dir_handle->next();
}

<?php
// Grab the "Global" settings from drupdates
$result = json_decode(exec('python ~/.drush/settings.py'), true);
$path = $result['workingDir']['value'];
$driver = $result['datastoreDriver']['value'];
$user = $result['datastoreSuperUser']['value'];
$pass = $result['datastoreSuperPword']['value'];
$port = $result['datastorePort']['value'];
$host = $result['datastoreHost']['value'];
$webroot = $result['webrootDir']['value'];

// I'm not sure why but if you keep $result populated you get ghost aliases who
// values are the same as the $result array elelment names
$result = array();
$aliases = array();
$dir_handle = new DirectoryIterator($path);
while($dir_handle->valid()) {
  if($dir_handle->isDir() && !$dir_handle->isDot()) {
    $basename = $dir_handle->getBasename();
    $root = $dir_handle->getPathname();
    $root = $webroot != "" ? $root : $root . $webroot;
    $aliases[$basename] = array(
      'uri' => 'http://localhost/' . $basename,
      'root' => $root,
      'databases' => array(
        'default' => array(
          'default' => array(
            'driver' => $driver,
            'username' => $user,
            'password' => $pass,
            'port' => $port,
            'host' => $host,
            'database' => $basename,
          ),
        ),
      ),
    );
  }
  $dir_handle->next();
}

Fix error in site alias files conditional if


<?php

namespace REBELinBLUE\Deployer\Console\Commands;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Foundation\Bus\DispatchesJobs;
use REBELinBLUE\Deployer\Jobs\UpdateGitMirror;
use REBELinBLUE\Deployer\Project;

/**
 * Updates the mirrors for all git repositories.
 */
class UpdateGitMirrors extends Command
{
    use DispatchesJobs;

    const UPDATES_TO_QUEUE         = 3;
    const UPDATE_FREQUENCY_MINUTES = 5;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'deployer:update-mirrors';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Pulls in updates for git mirrors';

    /**
     * Execute the console command.
     *
     * @return mixed
     *
     * @dispatches UpdateGitMirror
     */
    public function handle()
    {
        $last_mirrored_since = Carbon::now()->subMinutes(self::UPDATE_FREQUENCY_MINUTES);
        $todo                = self::UPDATES_TO_QUEUE;

        Project::where('last_mirrored', '<', $last_mirrored_since)->chunk($todo, function ($projects) {
            foreach ($projects as $project) {
                $this->dispatch(new UpdateGitMirror($project));
            }
        });
    }
}

<?php

namespace REBELinBLUE\Deployer\Console\Commands;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Foundation\Bus\DispatchesJobs;
use REBELinBLUE\Deployer\Jobs\UpdateGitMirror;
use REBELinBLUE\Deployer\Project;

/**
 * Updates the mirrors for all git repositories.
 */
class UpdateGitMirrors extends Command
{
    use DispatchesJobs;

    const UPDATES_TO_QUEUE         = 3;
    const UPDATE_FREQUENCY_MINUTES = 5;

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'deployer:update-mirrors';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Pulls in updates for git mirrors';

    /**
     * Execute the console command.
     *
     * @return mixed
     *
     * @dispatches UpdateGitMirror
     */
    public function handle()
    {
        $last_mirrored_since = Carbon::now()->subMinutes(self::UPDATE_FREQUENCY_MINUTES);
        $todo                = self::UPDATES_TO_QUEUE;

        $projects = Project::where('last_mirrored', '<', $last_mirrored_since)->orWhereNull('last_mirrored');
        $projects->chunk($todo, function ($projects) {
            foreach ($projects as $project) {
                $this->dispatch(new UpdateGitMirror($project));
            }
        });
    }
}

Fix console script to mirror git repos even if it has never been done before


<?php

namespace TypiCMS\Modules\Users\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Spatie\QueryBuilder\AllowedFilter;
use Spatie\QueryBuilder\QueryBuilder;
use TypiCMS\Modules\Core\Filters\FilterOr;
use TypiCMS\Modules\Core\Http\Controllers\BaseApiController;

class ApiController extends BaseApiController
{
    public function index(Request $request): LengthAwarePaginator
    {
        $data = QueryBuilder::for(config('auth.providers.users.model'))
            ->allowedSorts(['first_name', 'last_name', 'email', 'superuser'])
            ->allowedFilters([
                AllowedFilter::custom('first_name,last_name,email', new FilterOr()),
            ])
            ->paginate($request->input('per_page'));

        return $data;
    }

    public function updatePreferences(Request $request): void
    {
        $user = $request->user();
        $user->preferences = array_merge((array) $user->preferences, request()->all());
        $user->save();
    }

    public function destroy($userId): JsonResponse
    {
        $user = app(config('auth.providers.users.model'))->findOrFail($userId);
        if (method_exists($user, 'mollieCustomerFields')) {
            if ($user->hasRunningSubscription()) {
                return response()->json([
                    'error' => true,
                    'message' => __('User can not be deleted because he has a running subscription.')
                ]);
            }
        }
        $deleted = $user->delete();

        return response()->json([
            'error' => !$deleted,
        ]);
    }
}

<?php

namespace TypiCMS\Modules\Users\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Spatie\QueryBuilder\AllowedFilter;
use Spatie\QueryBuilder\QueryBuilder;
use TypiCMS\Modules\Core\Filters\FilterOr;
use TypiCMS\Modules\Core\Http\Controllers\BaseApiController;

class ApiController extends BaseApiController
{
    public function index(Request $request): LengthAwarePaginator
    {
        $data = QueryBuilder::for(config('auth.providers.users.model'))
            ->allowedSorts(['first_name', 'last_name', 'email', 'superuser'])
            ->allowedFilters([
                AllowedFilter::custom('first_name,last_name,email', new FilterOr()),
            ])
            ->paginate($request->input('per_page'));

        return $data;
    }

    public function updatePreferences(Request $request): void
    {
        $user = $request->user();
        $user->preferences = array_merge((array) $user->preferences, request()->all());
        $user->save();
    }

    public function destroy($userId): JsonResponse
    {
        $user = app(config('auth.providers.users.model'))->findOrFail($userId);
        if (method_exists($user, 'mollieCustomerFields')) {
            if ($user->hasRunningSubscription()) {
                return response()->json([
                    'error' => true,
                    'message' => __('User can not be deleted because he has a running subscription.')
                ], 403);
            }
        }
        $deleted = $user->delete();

        return response()->json([
            'error' => !$deleted,
        ]);
    }
}

Set response code as 403

Set response code as 403


<?php

namespace TmlpStats\Policies;

use TmlpStats\User;

class ReportTokenPolicy extends Policy
{
    /**
     * Create a new policy instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Can $user view the full list of reportTokens?
     *
     * @param User $user
     * @return bool
     */
    public function index(User $user)
    {
        return false; // admin only
    }

    /**
     * Can user view the ReportToken's URL?
     *
     * @param User $user
     * @return bool
     */
    public function readLink(User $user)
    {
        return $user->hasRole('globalStatistician');
    }
}

<?php
namespace TmlpStats\Policies;

use TmlpStats\User;

class ReportTokenPolicy extends Policy
{
    /**
     * Create a new policy instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Can $user view the full list of reportTokens?
     *
     * @param User $user
     * @return bool
     */
    public function index(User $user)
    {
        return false; // admin only
    }

    /**
     * Can user view the ReportToken's URL?
     *
     * @param User $user
     * @return bool
     */
    public function readLink(User $user)
    {
        return ($user->hasRole('globalStatistician') || $user->hasRole('localStatistician'));
    }
}

Allow local statisticians to view the ReportToken link links


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

namespace Darvin\UserBundle\Configuration;

use Darvin\ConfigBundle\Configuration\AbstractConfiguration;
use Darvin\ConfigBundle\Parameter\ParameterModel;

/**
 * Configuration
 *
 * @method array getNotificationEmails()
 */
class Configuration extends AbstractConfiguration
{
    /**
     * {@inheritdoc}
     */
    public function getModel()
    {
        return array(
            new ParameterModel('notification_emails', ParameterModel::TYPE_ARRAY, array(), array(
                'form' => array(
                    'options' => array(
                        'type'         => 'email',
                        'allow_add'    => true,
                        'allow_delete' => true,
                    ),
                ),
            )),
        );
    }

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

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

namespace Darvin\UserBundle\Configuration;

use Darvin\ConfigBundle\Configuration\AbstractConfiguration;
use Darvin\ConfigBundle\Parameter\ParameterModel;

/**
 * Configuration
 *
 * @method array getNotificationEmails()
 */
class Configuration extends AbstractConfiguration
{
    /**
     * {@inheritdoc}
     */
    public function getModel()
    {
        return array(
            new ParameterModel('notification_emails', ParameterModel::TYPE_ARRAY, array(), array(
                'form' => array(
                    'options' => array(
                        'type'         => 'Symfony\\Component\\Form\\Extension\\Core\\Type\\EmailType',
                        'allow_add'    => true,
                        'allow_delete' => true,
                    ),
                ),
            )),
        );
    }

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

Replace form type names with FQCN.

Replace form type names with FQCN.


<?php
/**
 * ChannelEngine Payment Method
 */
class Tritac_ChannelEngine_Model_Payment_Method_Channelengine extends Mage_Payment_Model_Method_Abstract {

    /**
     * System payment method code
     *
     * @var string
     */
    protected $_code = 'channelengine';

    public function isAvailable($quote = null)
    {
        if($quote->getIsSystem() && $quote->getPayment()->getMethod() == $this->_code) {
            return true;
        }

        return false;
    }
}

<?php
/**
 * ChannelEngine Payment Method
 */
class Tritac_ChannelEngine_Model_Payment_Method_Channelengine extends Mage_Payment_Model_Method_Abstract {

    /**
     * System payment method code
     *
     * @var string
     */
    protected $_code = 'channelengine';

    public function isAvailable($quote = null)
    {
        if(!is_null($quote) && $quote->getIsSystem() && $quote->getPayment()->getMethod() == $this->_code) {
            return true;
        }

        return false;
    }
}

Fix possible null error when isAvailable is called without a quote


<?php
class KalturaAuditTrailFileSyncCreateInfo extends KalturaAuditTrailInfo
{
	/**
	 * @var string
	 */
	public $version;

	/**
	 * @var KalturaAuditTrailFileSyncSubType
	 */
	public $objectSubType;

	/**
	 * @var int
	 */
	public $dc;

	/**
	 * @var bool
	 */
	public $original;

	/**
	 * @var KalturaAuditTrailFileSyncType
	 */
	public $fileType;
}

<?php
class KalturaAuditTrailFileSyncCreateInfo extends KalturaAuditTrailInfo
{
	/**
	 * @var string
	 */
	public $version;

	/**
	 * @var int
	 */
	public $objectSubType;

	/**
	 * @var int
	 */
	public $dc;

	/**
	 * @var bool
	 */
	public $original;

	/**
	 * @var KalturaAuditTrailFileSyncType
	 */
	public $fileType;
}

Use file sync sub type as is

Use file sync sub type as is

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


<?php

namespace Misantron\Silex\Provider\Adapter;

use Exception;
use Misantron\Silex\Provider\ConfigAdapter;
use Misantron\Silex\Provider\Exception\ComponentNotInstalledException;
use Misantron\Silex\Provider\Exception\ConfigurationParseException;
use SplFileInfo;
use Toml;

/**
 * Class TomlConfigAdapter
 * @package Misantron\Silex\Provider\Adapter
 */
class TomlConfigAdapter extends ConfigAdapter
{
    /**
     * @param SplFileInfo $file
     * @return array
     *
     * @throws ConfigurationParseException
     */
    protected function parse(SplFileInfo $file): array
    {
        try {
            $config = Toml::parseFile($file->getRealPath());
        } catch (Exception $e) {
            throw new ConfigurationParseException('Unable to parse config file: ' . $e->getMessage());
        }

        return $config;
    }

    /**
     * @return array
     */
    protected function configFileExtensions(): array
    {
        return ['toml'];
    }

    /**
     * @throws ComponentNotInstalledException
     */
    protected function assertComponentInstalled()
    {
        // @codeCoverageIgnoreStart
        if (!class_exists('\\Toml')) {
            throw new ComponentNotInstalledException('Toml parser component is not installed');
        }
        // @codeCoverageIgnoreEnd
    }
}

<?php

namespace Misantron\Silex\Provider\Adapter;

use Exception;
use Misantron\Silex\Provider\ConfigAdapter;
use Misantron\Silex\Provider\Exception\ComponentNotInstalledException;
use Misantron\Silex\Provider\Exception\ConfigurationParseException;
use SplFileInfo;
use Toml;

/**
 * Class TomlConfigAdapter
 * @package Misantron\Silex\Provider\Adapter
 */
class TomlConfigAdapter extends ConfigAdapter
{
    /**
     * @param SplFileInfo $file
     * @return array
     *
     * @throws ConfigurationParseException
     */
    protected function parse(SplFileInfo $file): array
    {
        try {
            $config = Toml::parseFile($file->getRealPath());
        } catch (Exception $e) {
            throw new ConfigurationParseException('Unable to parse config file: ' . $e->getMessage());
        }

        return json_decode(json_encode($config), true);
    }

    /**
     * @return array
     */
    protected function configFileExtensions(): array
    {
        return ['toml'];
    }

    /**
     * @throws ComponentNotInstalledException
     */
    protected function assertComponentInstalled()
    {
        // @codeCoverageIgnoreStart
        if (!class_exists('\\Toml')) {
            throw new ComponentNotInstalledException('Toml parser component is not installed');
        }
        // @codeCoverageIgnoreEnd
    }
}

Fix Toml config parsing adapter

Fix Toml config parsing adapter


<?php
// (c) Copyright 2002-2011 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"],basename(__FILE__)) !== false) {
  header("location: index.php");
  exit;
}

function module_search_wiki_page_info() {
	return array(
		'name' => tra('Search for Wiki Page'),
		'description' => tra('Search for a wiki page by name.'),
		'prefs' => array('feature_wiki'),
	);
}

function module_search_wiki_page( $mod_reference, $module_params ) {

}

<?php
// (c) Copyright 2002-2011 by authors of the Tiki Wiki CMS Groupware Project
//
// All Rights Reserved. See copyright.txt for details and a complete list of authors.
// Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details.
// $Id$

//this script may only be included - so its better to die if called directly.
if (strpos($_SERVER["SCRIPT_NAME"],basename(__FILE__)) !== false) {
  header("location: index.php");
  exit;
}

function module_search_wiki_page_info() {
	return array(
		'name' => tra('Search for Wiki Page'),
		'description' => tra('Search for a wiki page by name.'),
		'prefs' => array('feature_wiki'),
		'params' => array(
			'exact_match' => array(
				'name' => tra('Exact Match'),
				'description' => tra('Exact match checkbox unchecked by default if set to "n".') . " " . tr('Default: "y".'),
				'filter' => 'alpha'
			),
		),
	);
}

function module_search_wiki_page( $mod_reference, $module_params ) {
	global $smarty;
	$smarty->assign('exact_match', isset($module_params['exact_match']) ? $module_params['exact_match'] : 'y');
}

[ENH] Allow admin to set exact match checkbox to be unchecked by default.

git-svn-id: a7fabbc6a7c54ea5c67cbd16bd322330fd10cc35@36158 b456876b-0849-0410-b77d-98878d47e9d5


<?php

namespace Techlancaster\Bundle\WebBundle\Menu;

use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAware;

class Builder extends ContainerAware
{
    public function mainMenu(FactoryInterface $factory, array $options)
    {
        $menu = $factory->createItem('root');
        $menu->addChild('Home', array('route' => 'techlancaster_web_homepage'));
        $menu->addChild('Resources for Meetups', array('route' => 'techlancaster_resources'));
        $menu->addChild('Calendar', array('uri' => '/#calendar'));

        return $menu;
    }

    public function rightMenu(FactoryInterface $factory, array $options)
    {
        $menu = $factory->createItem('root');
        $menu->addChild('Meetup -  September 20th', array('route' => 'techlancaster_meetup'));
        $menu->addChild('Members', array('route' => 'fos_user_security_login'));

        if ($this->container->get('security.context')->isGranted('ROLE_USER')) {
            $menu['Members']->addChild('Logout', array('route' => 'fos_user_security_logout'));
        } else {
            $menu['Members']->addChild('Login', array('route' => 'fos_user_security_login'));
            $menu['Members']->addChild('Register', array('route' => 'fos_user_registration_register'));
        }

        return $menu;
    }
}

<?php

namespace Techlancaster\Bundle\WebBundle\Menu;

use Knp\Menu\FactoryInterface;
use Symfony\Component\DependencyInjection\ContainerAware;

class Builder extends ContainerAware
{
    public function mainMenu(FactoryInterface $factory, array $options)
    {
        $menu = $factory->createItem('root');
        $menu->addChild('Home', array('route' => 'techlancaster_web_homepage'));
        $menu->addChild('Resources for Meetups', array('route' => 'techlancaster_resources'));
        $menu->addChild('Calendar', array('uri' => '/#calendar'));

        return $menu;
    }

    public function rightMenu(FactoryInterface $factory, array $options)
    {
        $menu = $factory->createItem('root');
        $menu->addChild('Meetup -  October 18th', array('route' => 'techlancaster_meetup'));
        $menu->addChild('Members', array('route' => 'fos_user_security_login'));

        if ($this->container->get('security.context')->isGranted('ROLE_USER')) {
            $menu['Members']->addChild('Logout', array('route' => 'fos_user_security_logout'));
        } else {
            $menu['Members']->addChild('Login', array('route' => 'fos_user_security_login'));
            $menu['Members']->addChild('Register', array('route' => 'fos_user_registration_register'));
        }

        return $menu;
    }
}

Fix meetup date in builder

Fix meetup date in builder


<?php
declare(strict_types=1);
/**
 * @copyright Copyright (c) 2017 Joas Schilling <coding@schilljs.com>
 *
 * @author Joas Schilling <coding@schilljs.com>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * 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/>.
 *
 */

namespace OCA\AdminAudit\Actions;

class Console extends Action {
	/**
	 * @param $arguments
	 */
	public function runCommand(array $arguments) {
		if ($arguments[1] === '_completion') {
			// Don't log autocompletion
			return;
		}

		// Remove `./occ`
		array_shift($arguments);

		$this->log('Console command executed: %s',
			['arguments' => implode(' ', $arguments)],
			['arguments']
		);
	}
}

<?php
declare(strict_types=1);
/**
 * @copyright Copyright (c) 2017 Joas Schilling <coding@schilljs.com>
 *
 * @author Joas Schilling <coding@schilljs.com>
 *
 * @license GNU AGPL version 3 or any later version
 *
 * 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/>.
 *
 */

namespace OCA\AdminAudit\Actions;

class Console extends Action {
	/**
	 * @param $arguments
	 */
	public function runCommand(array $arguments) {
		if (!isset($arguments[1]) || $arguments[1] === '_completion') {
			// Don't log autocompletion
			return;
		}

		// Remove `./occ`
		array_shift($arguments);

		$this->log('Console command executed: %s',
			['arguments' => implode(' ', $arguments)],
			['arguments']
		);
	}
}

Check if array element is present before access

Signed-off-by: Daniel Kesselberg <1d6e1cf70ec6f9ab28d3ea4b27a49a77654d370e@danielkesselberg.de>


<?php

class CM_FormField_Site extends CM_FormField_Set_Select {

    /**
     * @param int                  $userInput
     * @param CM_Response_Abstract $response
     * @return CM_Site_Abstract
     */
    public function validate($userInput, CM_Response_Abstract $response) {
        $userInput = parent::validate($userInput, $response);
        return CM_Site_Abstract::factory($userInput);
    }

    public function _setup() {
        $valuesSet = array();
        foreach (CM_Site_Abstract::getAll() as $site) {
            $valuesSet[$site->getType()] = $site->getName();
        }
        $this->_params->set('values', $valuesSet);
        parent::_setup();
    }
}

<?php

class CM_FormField_Site extends CM_FormField_Set_Select {

    /**
     * @param int                  $userInput
     * @param CM_Response_Abstract $response
     * @return CM_Site_Abstract
     */
    public function validate($userInput, CM_Response_Abstract $response) {
        $userInput = parent::validate($userInput, $response);
        return CM_Site_Abstract::factory($userInput);
    }

    public function _setup() {
        $valuesSet = array();
        foreach (CM_Site_Abstract::getAll() as $site) {
            $valuesSet[$site->getType()] = $site->getName();
        }
        $this->_params->set('values', $valuesSet);
        $this->_params->set('labelsInValues', true);
        parent::_setup();
    }
}

Set labelInValues for site ff

Set labelInValues for site ff


<?php

declare(strict_types=1);

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('docusign_envelopes', static function (Blueprint $table): void {
            $table->unsignedInteger('sent_by')->nullable();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('docusign_envelopes', static function (Blueprint $table): void {
            $table->dropColumn('sent_by');
        });
    }
};

<?php

declare(strict_types=1);

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('docusign_envelopes', static function (Blueprint $table): void {
            $table->unsignedInteger('sent_by')->nullable();

            $table->foreign('sent_by')->references('id')->on('users');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('docusign_envelopes', static function (Blueprint $table): void {
            $table->dropColumn('sent_by');
        });
    }
};

Make sent_by a foreign key

Make sent_by a foreign key


<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Capsule\Manager as Capsule;

class DirectoryServiceAddBoundColumn extends Migration
{
    public function up()
    {
        $capsule = new Capsule();
        $capsule::schema()->table('directoryservice', function (Blueprint $table) {

            $table->string('bound');
            $table->index('bound');
        });
    }

  public function down()
  {

        $capsule = new Capsule();
        $capsule::schema()->table('directoryservice', function (Blueprint $table) {

            $table->dropColumn('bound');
      });
  }
}

<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Capsule\Manager as Capsule;

class DirectoryServiceAddBoundColumn extends Migration
{
    public function up()
    {
        $capsule = new Capsule();
        $capsule::schema()->table('directoryservice', function (Blueprint $table) {

            $table->string('bound')->nullable();
            $table->index('bound');
        });
    }

  public function down()
  {

        $capsule = new Capsule();
        $capsule::schema()->table('directoryservice', function (Blueprint $table) {

            $table->dropColumn('bound');
      });
  }
}

Make ds bound column nullable

Make ds bound column nullable


<?php

/*
 * This file is part of Composer.
 *
 * (c) Nils Adermann <naderman@naderman.de>
 *     Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Composer\DependencyResolver\Operation;

use Composer\Package\PackageInterface;

/**
 * Abstract solver operation class.
 *
 * @author Konstantin Kudryashov <ever.zet@gmail.com>
 */
abstract class SolverOperation implements OperationInterface
{
    protected $reason;

    /**
     * Initializes operation.
     *
     * @param string $reason operation reason
     */
    public function __construct($reason = null)
    {
        $this->reason = $reason;
    }

    /**
     * Returns operation reason.
     *
     * @return string
     */
    public function getReason()
    {
        return $this->reason;
    }

    /**
     * @param $lock bool Whether this is an operation on the lock file
     * @return string
     */
    public function show($lock)
    {
        throw new \RuntimeException('abstract method needs to be implemented in subclass, not marked abstract for compatibility with PHP <= 5.3.8');
    }
}

<?php

/*
 * This file is part of Composer.
 *
 * (c) Nils Adermann <naderman@naderman.de>
 *     Jordi Boggiano <j.boggiano@seld.be>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Composer\DependencyResolver\Operation;

use Composer\Package\PackageInterface;

/**
 * Abstract solver operation class.
 *
 * @author Konstantin Kudryashov <ever.zet@gmail.com>
 */
abstract class SolverOperation implements OperationInterface
{
    protected $reason;

    /**
     * Initializes operation.
     *
     * @param string $reason operation reason
     */
    public function __construct($reason = null)
    {
        $this->reason = $reason;
    }

    /**
     * Returns operation reason.
     *
     * @return string
     */
    public function getReason()
    {
        return $this->reason;
    }
}

Remove unnecessary implementation of interface method in abstract class


<?php
/**
 * @version     $Id$
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Languages
 * @copyright   Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
 * @license     GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link        http://www.nooku.org
 */

/**
 * Templates Toolbar Class
 *
 * @author      Ercan Ozkaya <http://nooku.assembla.com/profile/ercanozkaya>
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Languages
 */
class ComTemplatesControllerToolbarTemplates extends ComDefaultControllerToolbarDefault
{
    public function __construct(KConfig $config)
    {
        parent::__construct($config);

        $this->addSet();
    }

    protected function _initialize(KConfig $config)
    {
        $config->append(array(
            'auto_defaults' => false
        ));

        parent::_initialize($config);
    }

    protected function _commandSet(KControllerToolbarCommand $command)
    {
        $command->label = JText::_('Make Default');

        $command->append(array(
        	'attribs' => array(
                'data-action' => 'edit',
                'data-data'   => '{default:1}'
            )
        ));
    }
}

<?php
/**
 * @version     $Id$
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Languages
 * @copyright   Copyright (C) 2011 Timble CVBA and Contributors. (http://www.timble.net).
 * @license     GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
 * @link        http://www.nooku.org
 */

/**
 * Templates Toolbar Class
 *
 * @author      Ercan Ozkaya <http://nooku.assembla.com/profile/ercanozkaya>
 * @category	Nooku
 * @package     Nooku_Server
 * @subpackage  Languages
 */
class ComTemplatesControllerToolbarTemplates extends ComDefaultControllerToolbarDefault
{
    public function getCommands()
    {
        $this->reset()
             ->addSet();

        return parent::getCommands();
    }

    protected function _commandSet(KControllerToolbarCommand $command)
    {
        $command->label = JText::_('Make Default');

        $command->append(array(
        	'attribs' => array(
                'data-action' => 'edit',
                'data-data'   => '{default:1}'
            )
        ));
    }
}

Insert custom commands through the getCommands() function.


<?php

namespace Gregwar\ImageBundle\DependencyInjection;

use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\Config\FileLocator;

/**
 * Loading configuration
 *
 * @author Gregwar <g.passault@gmail.com>
 */
class GregwarImageExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $cacheDir = 'cache';

        $config = $configs[0];

        if (isset($config['cache_dir']))
            $cacheDir = $config['cache_dir'];

        $container->setParameter('gregwar_image.cache_dir', $cacheDir);

        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');
    }
}

<?php

namespace Gregwar\ImageBundle\DependencyInjection;

use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\Config\FileLocator;

/**
 * Loading configuration
 *
 * @author Gregwar <g.passault@gmail.com>
 */
class GregwarImageExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $cacheDir = 'cache';

        $config = array();
        foreach ($configs as $subConfig) {
            $config = array_merge($config, $subConfig);
        }

        if (isset($config['cache_dir']))
            $cacheDir = $config['cache_dir'];

        $container->setParameter('gregwar_image.cache_dir', $cacheDir);

        $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');
    }
}

Enable customization from multiple configuration files


<?php

/**
 * ProTalk
 *
 * Copyright (c) 2012-2013, ProTalk
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ProTalk\PageBundle\Tests\Controller;

use Liip\FunctionalTestBundle\Test\WebTestCase;
use Protalk\PageBundle\Controller\PageController;

class PageControllerTest extends WebTestCase
{
    public function setUp()
    {
        $this->loadFixtures(
            array(
                'Protalk\PageBundle\Tests\Fixtures\LoadPageData'
            )
        );
    }
    public function testGetHomepage()
    {
        $client = static::createClient();

        $client->request('GET', '/');
        $this->assertEquals(200, $client->getResponse()->getStatusCode());
    }

    public function testGetPage()
    {
        $client = static::createClient();

        $client->request('GET', '/page/news');

        $this->assertEquals(200, $client->getResponse()->getStatusCode());
        $this->assertContains('
News
', $client->getResponse()->getContent());
        $this->assertContains('
Some news page content.
', $client->getResponse()->getContent());
    }
}

<?php

/**
 * ProTalk
 *
 * Copyright (c) 2012-2013, ProTalk
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ProTalk\PageBundle\Tests\Controller;

use Liip\FunctionalTestBundle\Test\WebTestCase;
use Protalk\PageBundle\Controller\PageController;

class PageControllerTest extends WebTestCase
{
    public function setUp()
    {
        $this->loadFixtures(
            array(
                'Protalk\PageBundle\Tests\Fixtures\LoadPageData'
            )
        );
    }
    public function testGetHomepage()
    {
        $client = static::createClient();

        $client->request('GET', '/');
        $this->assertEquals(200, $client->getResponse()->getStatusCode());
    }

    public function testGetPageWithInvalidRequest()
    {
        $client = static::createClient();

        $client->request('GET', '/page/madeUpPage');

        $this->assertEquals(404, $client->getResponse()->getStatusCode());
    }

    public function testGetPageWithValidRequest()
    {
        $client = static::createClient();

        $client->request('GET', '/page/news');

        $this->assertEquals(200, $client->getResponse()->getStatusCode());
        $this->assertContains('
News
', $client->getResponse()->getContent());
        $this->assertContains('
Some news page content.
', $client->getResponse()->getContent());
    }
}

Add test for PageBundle when requesting an invalid page


<?php

/**
 * Define Robo commands for building and testing Drupal User Registry Codeception module.
 *
 * @see http://robo.li/
 */
class RoboFile extends \Robo\Tasks
{
    /**
     * @type string
     *   Location of directory containing source code.
     */
    const SRC_DIR = "src";

    /**
     * @type string
     *   Location of directory containing documentation files.
     */
    const DOCS_DIR = "docs";

    /**
     * @type string
     *   Location of directory containing Codeception tests.
     */
    const TESTS_DIR = "tests";

    /**
     * Generate PhpDocumentator files.
     */
    public function docsGenerate()
    {
        $this->taskExec(sprintf("phpdoc run -d %s -t %s", self::SRC_DIR, self::DOCS_DIR))
            ->run();
    }

    /**
     * Clean PhpDocumentor directory.
     */
    public function docsClean()
    {
        $this->taskCleanDir(self::DOCS_DIR)->run();
    }

    /**
     * Run (functional) tests.
     */
    public function testsRun()
    {
        // Still have to build the *Tester classes if we've just checked out.
        $this->taskExec("cd tests && vendor/bin/codecept build && cd -")->run();

        $this->taskCodecept("tests/vendor/bin/codecept")
            ->option("config", self::TESTS_DIR . "/tests/codeception.yml")
            ->suite("functional")
            ->run();
    }
}

<?php

/**
 * Define Robo commands for building and testing Drupal User Registry Codeception module.
 *
 * @see http://robo.li/
 */
class RoboFile extends \Robo\Tasks
{
    /**
     * @type string
     *   Location of directory containing source code.
     */
    const SRC_DIR = "src";

    /**
     * @type string
     *   Location of directory containing documentation files.
     */
    const DOCS_DIR = "docs";

    /**
     * @type string
     *   Location of directory containing Codeception tests.
     */
    const TESTS_DIR = "tests";

    /**
     * Generate PhpDocumentator files.
     */
    public function docsGenerate()
    {
        $this->taskExec(sprintf("phpdoc run -d %s -t %s", self::SRC_DIR, self::DOCS_DIR))
            ->run();
    }

    /**
     * Clean PhpDocumentor directory.
     */
    public function docsClean()
    {
        $this->taskCleanDir(self::DOCS_DIR)->run();
    }

    /**
     * Run (functional) tests.
     */
    public function testsRun()
    {
        // Still have to build the *Tester classes if we've just checked out.
        $this->taskExec("cd tests && vendor/bin/codecept build && cd -")->run();

        $this->taskCodecept(self::TESTS_DIR . DIRECTORY_SEPARATOR . "vendor/bin/codecept")
            ->option("config", self::TESTS_DIR  . DIRECTORY_SEPARATOR . "codeception.yml")
            ->suite("functional")
            ->run();
    }
}

Correct paths to Codeception etc.

Correct paths to Codeception etc.


<?php

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

declare(strict_types=1);

namespace Sylius\Component\Currency\Model;

use Sylius\Component\Resource\Model\TimestampableTrait;
use Symfony\Component\Intl\Currencies;

class Currency implements CurrencyInterface
{
    use TimestampableTrait;

    /** @var mixed */
    protected $id;

    /** @var string|null */
    protected $code;

    public function __construct()
    {
        $this->createdAt = new \DateTime();
    }

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

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

    /**
     * {@inheritdoc}
     */
    public function getName(): ?string
    {
        return Currencies::getName($this->getCode());
    }

    /**
     * {@inheritdoc}
     */
    public function getCode(): ?string
    {
        return $this->code;
    }

    /**
     * {@inheritdoc}
     */
    public function setCode(?string $code): void
    {
        $this->code = $code;
    }
}

<?php

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

declare(strict_types=1);

namespace Sylius\Component\Currency\Model;

use Sylius\Component\Resource\Model\TimestampableTrait;
use Symfony\Component\Intl\Currencies;

class Currency implements CurrencyInterface
{
    use TimestampableTrait;

    /** @var mixed */
    protected $id;

    /** @var string|null */
    protected $code;

    public function __construct()
    {
        $this->createdAt = new \DateTime();
    }

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

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

    /**
     * {@inheritdoc}
     */
    public function getName(): ?string
    {
        if (null === $code = $this->getCode()) {
            return null;
        }

        return Currencies::getName($code);
    }

    /**
     * {@inheritdoc}
     */
    public function getCode(): ?string
    {
        return $this->code;
    }

    /**
     * {@inheritdoc}
     */
    public function setCode(?string $code): void
    {
        $this->code = $code;
    }
}

Fix currency get name when it has no code


<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class BaseModel extends Model
{
    public $incrementing = false;

    public static function getTableName()
    {
        return with(new static)->getTable();
    }

    /**
     * Cast an attribute to a native PHP type.
     *
     * @param  string  $key
     * @param  mixed   $value
     * @return mixed
     */
    protected function castAttribute($key, $value)
    {
        // Run the parent cast rules in the parent method
        $value = parent::castAttribute($key, $value);

        if (is_null($value)) return $value;

        switch ($this->getCastType($key))
        {
            case 'date':
                return \Carbon\Carbon::createFromFormat('Y-m-d H:i', $value.' 00:00')->toIso8601String();
            case 'datetime':
                return \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $value)->toIso8601String();
            default:
                return $value;
        }
    }
}

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Bosnadev\Database\Traits\UuidTrait;

class BaseModel extends Model
{
    use UuidTrait;

    public $incrementing = false;

    public static function getTableName()
    {
        return with(new static)->getTable();
    }

    /**
     * Cast an attribute to a native PHP type.
     *
     * @param  string  $key
     * @param  mixed   $value
     * @return mixed
     */
    protected function castAttribute($key, $value)
    {
        // Run the parent cast rules in the parent method
        $value = parent::castAttribute($key, $value);

        if (is_null($value)) return $value;

        switch ($this->getCastType($key))
        {
            case 'date':
                return \Carbon\Carbon::createFromFormat('Y-m-d H:i', $value.' 00:00')->toIso8601String();
            case 'datetime':
                return \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $value)->toIso8601String();
            default:
                return $value;
        }
    }
}

Use the UuidTrait for models

Use the UuidTrait for models


Details for your app: <?php $this->utility->safe($name); ?>

        Name
        <?php $this->utility->safe($name); ?>

        Consumer Key
        <?php $this->utility->safe($id); ?>

        Consumer Secret
        <?php $this->utility->safe($clientSecret); ?>

        OAuth Token
        <?php $this->utility->safe($userToken); ?>

        OAuth Secret
        <?php $this->utility->safe($userSecret); ?>

        Type

          <?php $this->utility->safe($type); ?>
          <?php if($type !== Credential::typeAccess) { ?>
            (Only access tokens can be used)
          <?php } ?>

Details for your app: <?php $this->utility->safe($name); ?>

        Name
        <?php $this->utility->safe($name); ?>

        consumerKey =
        <?php $this->utility->safe($id); ?>

        consumerSecret =
        <?php $this->utility->safe($clientSecret); ?>

        token =
        <?php $this->utility->safe($userToken); ?>

        tokenSecret =
        <?php $this->utility->safe($userSecret); ?>

        Type

          <?php $this->utility->safe($type); ?>
          <?php if($type !== Credential::typeAccess) { ?>
            (Only access tokens can be used)
          <?php } ?>

Change credential text to use the same identifiers as the commandline tools

This allows a single simple cut/paste into a config file.


<?php
namespace IonutMilica\LaravelSettings;

use IonutMilica\LaravelSettings\Drivers\Database;
use IonutMilica\LaravelSettings\Drivers\Json;
use IonutMilica\LaravelSettings\Drivers\Memory;
use Illuminate\Support\Manager;

class DriversManager extends Manager
{
    /**
     * Get the default driver name.
     *
     * @return string
     */
    public function getDefaultDriver()
    {
        return $this->config('settings.driver');
    }

    /**
     * Creates a new memory driver for settings
     *
     * @return Memory
     */
    public function createMemoryDriver()
    {
        return new Memory($this->app['config']);
    }

    /**
     * Creates a new database driver for settings
     *
     * @return Database
     */
    public function createDatabaseDriver()
    {
        return new Database($this->app['db']);
    }

    /**
     * Creates a new json driver for settings
     *
     * @return Json
     */
    public function createJsonDriver()
    {
        return new Json($this->config('settings.json_file'));
    }

    /**
     * Get config data
     *
     * @param $key
     * @param null $default
     * @return mixed
     */
    public function config($key, $default = null)
    {
        return $this->app['config']->get($key, $default);
    }

}

<?php
namespace IonutMilica\LaravelSettings;

use IonutMilica\LaravelSettings\Drivers\Database;
use IonutMilica\LaravelSettings\Drivers\Json;
use IonutMilica\LaravelSettings\Drivers\Memory;
use Illuminate\Support\Manager;

class DriversManager extends Manager
{
    /**
     * Get the default driver name.
     *
     * @return string
     */
    public function getDefaultDriver()
    {
        return $this->config('settings.driver');
    }

    /**
     * Creates a new memory driver for settings
     *
     * @return Memory
     */
    public function createMemoryDriver()
    {
        return new Memory($this->app['config']);
    }

    /**
     * Creates a new database driver for settings
     *
     * @return Database
     */
    public function createDatabaseDriver()
    {
        return new Database($this->app['db'], $this->config('settings.table'));
    }

    /**
     * Creates a new json driver for settings
     *
     * @return Json
     */
    public function createJsonDriver()
    {
        return new Json($this->config('settings.json_file'));
    }

    /**
     * Get config data
     *
     * @param $key
     * @param null $default
     * @return mixed
     */
    public function config($key, $default = null)
    {
        return $this->app['config']->get($key, $default);
    }

}

Create Database driver with configured Table name


<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/

Route::get('/products', 'ProductsController@getProducts');

Route::get('/product/{id}', 'ProductController@getProduct');

Route::get('/categories', 'CategoriesController@getCategories');

Route::get('/attributes/{name}', 'AttributesController@getOptions');

Route::get('/basket', 'BasketController@getItems');
Route::get('/basket/add/{id}/{quantity}', 'BasketController@addItem');
Route::get('/basket/remove/{id}', 'BasketController@removeItem');

Route::get('/currencies', 'CurrenciesController@getCurrencies');

Route::get('/account', 'AccountController@getAccount');
Route::post('/account/login', 'AccountController@login');
Route::get('/account/logout', 'AccountController@logout');
Route::post('/account/register', 'AccountController@register');

<?php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::get(
    '/', function () {
    return null;
}

);
Route::get('/products', 'ProductsController@getProducts');

Route::get('/product/{id}', 'ProductController@getProduct');

Route::get('/categories', 'CategoriesController@getCategories');

Route::get('/attributes/{name}', 'AttributesController@getOptions');

Route::get('/basket', 'BasketController@getItems');
Route::get('/basket/add/{id}/{quantity}', 'BasketController@addItem');
Route::get('/basket/remove/{id}', 'BasketController@removeItem');

Route::get('/currencies', 'CurrenciesController@getCurrencies');

Route::get('/account', 'AccountController@getAccount');
Route::post('/account/login', 'AccountController@login');
Route::get('/account/logout', 'AccountController@logout');
Route::post('/account/register', 'AccountController@register');

Index routing changed return null.

Index routing changed return null.


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

namespace Zend\Stdlib\Hydrator\Filter;

use ReflectionException;
use ReflectionMethod;
use Zend\Stdlib\Exception\InvalidArgumentException;

class NumberOfParameterFilter implements FilterInterface
{
    /**
     * The number of parameters beeing accepted
     * @var int
     */
    protected $numberOfParameters = null;

    /**
     * @param int $numberOfParameters Number of accepted parameters
     */
    public function __construct($numberOfParameters = 0)
    {
        $this->numberOfParameters = (int) $numberOfParameters;
    }

    /**
     * @param string $property the name of the property
     * @return bool
     * @throws InvalidArgumentException
     */
    public function filter($property)
    {
        try {
            $reflectionMethod = new ReflectionMethod($property);
        } catch (ReflectionException $exception) {
            throw new InvalidArgumentException(
                "Method $property doesn't exist"
            );
        }

        if ($reflectionMethod->getNumberOfParameters() !== $this->numberOfParameters) {
            return false;
        }

        return true;
    }
}

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

namespace Zend\Stdlib\Hydrator\Filter;

use ReflectionException;
use ReflectionMethod;
use Zend\Stdlib\Exception\InvalidArgumentException;

class NumberOfParameterFilter implements FilterInterface
{
    /**
     * The number of parameters beeing accepted
     * @var int
     */
    protected $numberOfParameters = null;

    /**
     * @param int $numberOfParameters Number of accepted parameters
     */
    public function __construct($numberOfParameters = 0)
    {
        $this->numberOfParameters = (int) $numberOfParameters;
    }

    /**
     * @param string $property the name of the property
     * @return bool
     * @throws InvalidArgumentException
     */
    public function filter($property)
    {
        try {
            $reflectionMethod = new ReflectionMethod($property);
        } catch (ReflectionException $exception) {
            throw new InvalidArgumentException(
                "Method $property doesn't exist"
            );
        }

        return $reflectionMethod->getNumberOfParameters() === $this->numberOfParameters;
    }
}

Return boolean instead of if statement.

Return boolean instead of if statement.


<?php

namespace Talal\LabelPrinter\Mode;

use Talal\LabelPrinter\Command\CommandInterface;

abstract class Mode
{
    /**
     * @var array
     */
    protected $commands = [];

    /**
     * @var resource
     */
    protected $resource;

    /**
     * @param resource $resource
     */
    public function setResource($resource)
    {
        if (! is_resource($resource)) {
            throw new \InvalidArgumentException('An invalid resource has been provided.');
        }

        $this->resource = $resource;
    }

    /**
     * @param CommandInterface $command
     */
    public function addCommand(CommandInterface $command)
    {
        $this->commands[] = $command;
    }

    /**
     * @return CommandInterface[]
     */
    public function getCommands()
    {
        return $this->commands;
    }

    /**
     * @param string    $data
     * @return string
     */
    public function sendCommand($data)
    {
        fwrite($this->resource, $data);

        return $data;
    }

    /**
     * Send the print-label command
     *
     * @return void
     */
    abstract public function process();
}

<?php

namespace Talal\LabelPrinter\Mode;

use Talal\LabelPrinter\Command\CommandInterface;

abstract class Mode
{
    /**
     * @var array
     */
    protected $commands = [];

    /**
     * @var resource
     */
    protected $resource;

    /**
     * @param resource $resource
     */
    public function setResource($resource)
    {
        if (! is_resource($resource)) {
            throw new \InvalidArgumentException('An invalid resource has been provided.');
        }

        $this->resource = $resource;
    }

    /**
     * Closes the connection resource.
     */
    public function closeResource()
    {
        fclose($this->resource);
    }

    /**
     * @param CommandInterface $command
     */
    public function addCommand(CommandInterface $command)
    {
        $this->commands[] = $command;
    }

    /**
     * @return CommandInterface[]
     */
    public function getCommands()
    {
        return $this->commands;
    }

    /**
     * @param string    $data
     * @return string
     */
    public function sendCommand($data)
    {
        fwrite($this->resource, $data);

        return $data;
    }

    /**
     * Send the print-label command
     *
     * @return void
     */
    abstract public function process();
}

Add functionality to close a connection

Add functionality to close a connection

Allows to close a connection directly via the Mode instance.
This improves the testability of label print code, as the printer
and its dependencies can be replaced with mocks in unit/integration tests.

The original direct fclose() call according to the docs would prevent such uses.


<?php

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

namespace spec\Sylius\Bundle\CoreBundle\EventListener;

use PhpSpec\ObjectBehavior;

class OrderCurrencyListenerSpec extends ObjectBehavior
{
    /**
     * @param Sylius\Bundle\MoneyBundle\Context\CurrencyContextInterface $currencyContext
     */
    function let($currencyContext)
    {
        $this->beConstructedWith($currencyContext);
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('Sylius\Bundle\CoreBundle\EventListener\OrderCurrencyListener');
    }

    /**
     * @param Symfony\Component\EventDispatcher\GenericEvent $event
     * @param \stdClass                                      $invalidSubject
     */
    function it_throws_exception_if_event_has_non_order_subject($event, $invalidSubject)
    {
        $event->getSubject()->willReturn($invalidSubject);

        $this
            ->shouldThrow('InvalidArgumentException')
            ->duringProcessOrderCurrency($event)
        ;
    }

    /**
     * @param Symfony\Component\EventDispatcher\GenericEvent $event
     * @param Sylius\Bundle\CoreBundle\Model\OrderInterface  $order
     */
    function it_sets_currency_on_order($currencyContext, $event, $order)
    {
        $event->getSubject()->willReturn($order);
        $currencyContext->getCurrency()->shouldBeCalled()->willReturn('PLN');

        $this->processOrderCurrency($event);
    }
}

<?php

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

namespace spec\Sylius\Bundle\CoreBundle\EventListener;

use PhpSpec\ObjectBehavior;

class OrderCurrencyListenerSpec extends ObjectBehavior
{
    /**
     * @param Sylius\Bundle\MoneyBundle\Context\CurrencyContextInterface $currencyContext
     */
    function let($currencyContext)
    {
        $this->beConstructedWith($currencyContext);
    }

    function it_is_initializable()
    {
        $this->shouldHaveType('Sylius\Bundle\CoreBundle\EventListener\OrderCurrencyListener');
    }

    /**
     * @param Sylius\Bundle\CartBundle\Event\CartEvent       $event
     * @param \stdClass                                      $invalidSubject
     */
    function it_throws_exception_if_event_has_non_order_subject($event, $invalidSubject)
    {
        $event->getCart()->willReturn($invalidSubject);

        $this
            ->shouldThrow('InvalidArgumentException')
            ->duringProcessOrderCurrency($event)
        ;
    }

    /**
     * @param Sylius\Bundle\CartBundle\Event\CartEvent       $event
     * @param Sylius\Bundle\CoreBundle\Model\OrderInterface  $order
     */
    function it_sets_currency_on_order($currencyContext, $event, $order)
    {
        $event->getCart()->willReturn($order);
        $currencyContext->getCurrency()->shouldBeCalled()->willReturn('PLN');

        $this->processOrderCurrency($event);
    }
}

Fix the order currency listener spec

Fix the order currency listener spec


    uri() }}" title="{{ $object->title }}">
        {{ $object->title }}

            present()->image(null, 200) }}" width="{{ $object->image->width }}" height="{{ $object->image->height }}" alt="">

    uri() }}" title="{{ $object->title }}">

{{ $object->title }}

            @empty (!$object->image)
            present()->image(null, 200) }}" width="{{ $object->image->width }}" height="{{ $object->image->height }}" alt="{{ $object->image->alt_attribute }}">
            @endempty

Check empty image + missing alt attribute.


<?php

/**
 * Factory class for providing Localization implementations
 * @author M2Mobi, Heinz Wiesinger
 */
class L10nFactory
{

    /**
     * Instance of the L10nProvider
     * @var array
     */
    private static $lprovider;

    /**
     * Constructor
     */
    public function __construct()
    {

    }

    /**
     * Destructor
     */
    public function __destruct()
    {

    }

    /**
     * This method returns an object with the appropriate localization
     * implementation provider
     * @param String $provider The localization implementation requested
     * @param String $language POSIX locale definition
     * @return L10nProvider $return Instance of the localization provider requested
     */
    public static function get_localization($provider, $language)
    {
        require_once("class.l10nprovider.inc.php");
        switch($provider)
        {
            case "php":
                if (!isset(self::$lprovider[$provider]))
                {
                    require_once("class.l10nproviderphp.inc.php");
                    self::$lprovider[$provider] = new L10nProviderPHP($language);
                }

                return self::$lprovider[$provider];
                break;
            case "gettext":
            default:
                if (!isset(self::$lprovider[$provider]))
                {
                    require_once("class.l10nprovidergettext.inc.php");
                    self::$lprovider[$provider] = new L10nProviderGettext($language);
                }

                return self::$lprovider[$provider];
                break;
        }
    }
}

?>

<?php

/**
 * Factory class for providing Localization implementations
 * @author M2Mobi, Heinz Wiesinger
 */
class L10nFactory
{

    /**
     * Instance of the L10nProvider
     * @var array
     */
    private static $lprovider;

    /**
     * This method returns an object with the appropriate localization
     * implementation provider
     * @param String $provider The localization implementation requested
     * @param String $language POSIX locale definition
     * @return L10nProvider $return Instance of the localization provider requested
     */
    public static function get_localization($provider, $language)
    {
        require_once("class.l10nprovider.inc.php");
        switch($provider)
        {
            case "php":
                if (!isset(self::$lprovider[$provider]))
                {
                    require_once("class.l10nproviderphp.inc.php");
                    self::$lprovider[$provider] = new L10nProviderPHP($language);
                }

                return self::$lprovider[$provider];
                break;
            case "gettext":
            default:
                if (!isset(self::$lprovider[$provider]))
                {
                    require_once("class.l10nprovidergettext.inc.php");
                    self::$lprovider[$provider] = new L10nProviderGettext($language);
                }

                return self::$lprovider[$provider];
                break;
        }
    }
}

?>

system: Remove constructor/destructor from static L10nFactory


<?php
declare(strict_types=1);

namespace Marein\Nchan\Tests\TestServer;

use PHPUnit\Framework\TestListener;
use PHPUnit\Framework\TestListenerDefaultImplementation;
use PHPUnit\Framework\TestSuite;
use Symfony\Component\Process\Process;

final class PhpUnitStartServerListener implements TestListener
{
    use TestListenerDefaultImplementation;

    /**
     * @var string
     */
    private $suiteName;

    /**
     * @var string
     */
    private $socket;

    /**
     * @var string
     */
    private $documentRoot;

    /**
     * PhpUnitStartServerListener constructor.
     *
     * @param string $suiteName
     * @param string $socket
     * @param string $documentRoot
     */
    public function __construct(string $suiteName, string $socket, string $documentRoot)
    {
        $this->suiteName = $suiteName;
        $this->socket = $socket;
        $this->documentRoot = $documentRoot;
    }

    /**
     * @inheritdoc
     */
    public function startTestSuite(TestSuite $suite): void
    {
        if ($suite->getName() === $this->suiteName) {
            $process = new Process(
                sprintf(
                    'php -S %s %s',
                    $this->socket,
                    $this->documentRoot
                )
            );
            $process->start();

            // Wait for the server.
            sleep(1);
        }
    }
}

<?php
declare(strict_types=1);

namespace Marein\Nchan\Tests\TestServer;

use PHPUnit\Framework\TestListener;
use PHPUnit\Framework\TestListenerDefaultImplementation;
use PHPUnit\Framework\TestSuite;
use Symfony\Component\Process\Process;

final class PhpUnitStartServerListener implements TestListener
{
    use TestListenerDefaultImplementation;

    /**
     * @var string
     */
    private $suiteName;

    /**
     * @var string
     */
    private $socket;

    /**
     * @var string
     */
    private $documentRoot;

    /**
     * PhpUnitStartServerListener constructor.
     *
     * @param string $suiteName
     * @param string $socket
     * @param string $documentRoot
     */
    public function __construct(string $suiteName, string $socket, string $documentRoot)
    {
        $this->suiteName = $suiteName;
        $this->socket = $socket;
        $this->documentRoot = $documentRoot;
    }

    /**
     * @inheritdoc
     */
    public function startTestSuite(TestSuite $suite): void
    {
        if ($suite->getName() === $this->suiteName) {
            $process = new Process(
                [
                    'php',
                    '-S',
                    $this->socket,
                    $this->documentRoot
                ]
            );
            $process->start();

            // Wait for the server.
            sleep(1);
        }
    }
}

Use Process(array) instead of Process(string)


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Listabierta\Bundle\MunicipalesBundle\Form\Type\TownStep1Type;

class CandidateController extends Controller
{
	public function indexAction(Request $request = NULL)
	{
		$this->step1Action($request);
	}

	public function step1Action($address = NULL, Request $request = NULL)
	{
		$form = $this->createForm(new TownStep1Type(), NULL, array(
				'action' => $this->generateUrl('candidate_step1', array('address' => $address)),
				'method' => 'POST',
		)
		);

		$form->handleRequest($request);

		if ($form->isValid())
		{

		}

		return $this->render('MunicipalesBundle:Candidate:step1.html.twig', array(
				'address' => $address,
				'form' => $form->createView(),
				'errors' => $form->getErrors()
		));
	}
}

<?php

namespace Listabierta\Bundle\MunicipalesBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Listabierta\Bundle\MunicipalesBundle\Form\Type\TownStep1Type;

class CandidateController extends Controller
{
	public function indexAction(Request $request = NULL)
	{
		$this->step1Action($request);
	}

	public function step1Action($address = NULL, Request $request = NULL)
	{
		$entity_manager = $this->getDoctrine()->getManager();

		$admin_candidacy_repository = $entity_manager->getRepository('Listabierta\Bundle\MunicipalesBundle\Entity\AdminCandidacy');

		$address_slug = $this->get('slugify')->slugify($address);

		$admin_candidacy = $admin_candidacy_repository->findOneBy(array('address' => $address_slug));

		if(empty($admin_candidacy))
		{
			throw $this->createNotFoundException('No existe la candidatura de administrador para cargar la dirección ' . $address_slug);
		}

		$form = $this->createForm(new TownStep1Type(), NULL, array(
				'action' => $this->generateUrl('candidate_step1', array('address' => $address)),
				'method' => 'POST',
		)
		);

		$form->handleRequest($request);

		if ($form->isValid())
		{

		}

		return $this->render('MunicipalesBundle:Candidate:step1.html.twig', array(
				'address' => $address,
				'town' => $admin_candidacy->getTown(),
				'form' => $form->createView(),
				'errors' => $form->getErrors()
		));
	}
}

Check address slug for candidate first step


<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('jwt.auth')->get('v1/user', function (Request $request) {
    return $request->user();
});

Route::group(['prefix' => 'v1/', 'middleware' => ['jwt.auth', 'cas.auth']], function () {
    Route::post('faset', 'FasetVisitController@visit');
    Route::get('faset', 'FasetVisitController@list')->middleware('can:administer');
    Route::get('faset/{id}', 'FasetVisitController@show')->middleware('can:administer');
    Route::put('faset/{id}', 'FasetVisitController@update')->middleware('can:administer');
    Route::middleware('can:administer')->resource('users', 'UserController', ['except' => ['create', 'edit']]);
    Route::middleware('can:administer')->resource('events', 'EventController', ['except' => ['create', 'edit']]);
});

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('jwt.auth')->get('v1/user', function (Request $request) {
    return $request->user();
});

Route::group(['prefix' => 'v1/', 'middleware' => ['jwt.auth', 'cas.auth']], function () {
    Route::post('faset', 'FasetVisitController@visit');
    Route::get('faset', 'FasetVisitController@list')->middleware('can:administer');
    Route::get('faset/{id}', 'FasetVisitController@show')->middleware('can:administer');
    Route::put('faset/{id}', 'FasetVisitController@update')->middleware('can:administer');
    Route::get('notification/send', 'NotificationController@sendNotification')->middleware('can:administer');
    Route::middleware('can:administer')->resource('users', 'UserController', ['except' => ['create', 'edit']]);
    Route::middleware('can:administer')->resource('events', 'EventController', ['except' => ['create', 'edit']]);
});

Add route to hit notification controller


<?php
/*
 * This file is part of the wp-magnify/core package.
 *
 * (c) Christopher Davis <http://christopherdavis.me>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/**
 * Fetches the default instance of the `Magnify` class.
 *
 * @return  Magnify\Core\Magnify
 */
function magnify()
{
    return \Magnify::getInstance();
}

/**
 * Hooked into `plugins_loaded` to kick things off. Extensions should hook into
 * `magnify_loaded` to extend this plugin.
 *
 * @return  void
 */
function magnify_core_load()
{
    $magnify = magnify();

    do_action('magnify_loaded', $magnify);
}

function magnify_act($hook, ...$args)
{
    do_action(magnify_hook($hook), ...$args);
}

function magnify_filter($hook, ...$args)
{
    return apply_filters(magnify_hook($hook), ...$args);
}

function magnify_hook($hook)
{
    return sprintf('magnify_%s', $hook);
}

Introduce Some Abstractions Around Hooks


<?php

use Silex\Provider\MonologServiceProvider;
use Silex\Provider\WebProfilerServiceProvider;

// include the prod configuration
require __DIR__.'/prod.php';

// enable the debug mode
$app['debug'] = true;

$app->register(new MonologServiceProvider(), array(
    'monolog.logfile' => __DIR__.'/../var/logs/silex_dev.log',
));

$app->register(new WebProfilerServiceProvider(), array(
    'profiler.cache_dir' => __DIR__.'/../var/cache/profiler',
));

<?php

use Silex\Provider\MonologServiceProvider;
use Silex\Provider\WebProfilerServiceProvider;
use Silex\Provider\DebugServiceProvider;

// include the prod configuration
require __DIR__.'/prod.php';

// enable the debug mode
$app['debug'] = true;

$app->register(new MonologServiceProvider(), array(
    'monolog.logfile' => __DIR__.'/../var/logs/silex_dev.log',
));

$app->register(new WebProfilerServiceProvider(), array(
    'profiler.cache_dir' => __DIR__.'/../var/cache/profiler',
    'profiler.mount_prefix' => '/_silex/profiler',
));

$app->register(new DebugServiceProvider(), array(
    'debug.max_items' => 250, // this is the default
    'debug.max_string_length' => -1, // this is the default
));

Add DebugServiceProvider, change profiler mount point.


<?php
/** @var OC_L10N $l */
/** @var array $_ */
?>

  <form id="ownpad_settings">

<?php p($l->t('Collaborative documents'));?>

<?php p($l->t('This is used to link collaborative documents inside ownCloud.')); ?>

      <?php p($l->t('Etherpad Host')); ?>
      <input type="text" name="ownpad_etherpad_host" id="ownpad_etherpad_host"
	     value="<?php p($_['ownpad_etherpad_host']); ?>"
             placeholder="http://lite.framapad.org" />

      <?php p($l->t('Ethercalc Host')); ?>
      <input type="text" name="ownpad_ethercalc_host" id="ownpad_ethercalc_host"
	     value="<?php p($_['ownpad_ethercalc_host']); ?>"
             placeholder="http://wwW.framacalc.org" />

      <?php p($l->t('Saved')); ?>

<?php
/** @var OC_L10N $l */
/** @var array $_ */
?>

  <form id="ownpad_settings">

<?php p($l->t('Collaborative documents'));?>

<?php p($l->t('This is used to link collaborative documents inside ownCloud.')); ?>

      <?php p($l->t('Etherpad Host')); ?>
      <input type="text" name="ownpad_etherpad_host" id="ownpad_etherpad_host"
	     value="<?php p($_['ownpad_etherpad_host']); ?>"
             placeholder="https://mensuel.framapad.org" />

      <?php p($l->t('Ethercalc Host')); ?>
      <input type="text" name="ownpad_ethercalc_host" id="ownpad_ethercalc_host"
	     value="<?php p($_['ownpad_ethercalc_host']); ?>"
             placeholder="https://framacalc.org" />

      <?php p($l->t('Saved')); ?>

Update placeholders in ownpad configuration template


@extends('app')

@section('content')

					@if(\Auth::user()->isOwner($business))
						{!! Icon::star() !!} {!! link_to(route('manager.business.show', $business->id), $business->name) !!}
					@else
						{{ $business->name }}
					@endif

					{!! Button::normal(trans('user.appointments.btn.book'))->asLinkTo( route('user.booking.book') ) !!}

@endsection

@extends('app')

@section('content')

					@if(\Auth::user()->isOwner($business))
						{!! Icon::star() !!} {!! link_to(route('manager.business.show', $business), $business->name) !!}
					@else
						{{ $business->name }}
					@endif

					{{ $business->description }}

					{!! Button::normal(trans('user.appointments.btn.book'))->asLinkTo( route('user.booking.book') ) !!}

@endsection

Enhance Business show user page

Enhance Business show user page


<?php
use GherkinViewer\services\GherkinParser;

require_once __DIR__ . '/../vendor/autoload.php';

$app = new Silex\Application();

$app->register(new Silex\Provider\TwigServiceProvider(), array(
    'twig.path' => __DIR__ . '/views',
));

$app['GherkinParser'] = function () {
    return new GherkinParser();
};

$app['FeatureExtractor'] = function() use ($app) {
    return new \GherkinViewer\services\FeatureExtractor(__DIR__ . '/../features/', $app['GherkinParser']);
};

$app->get('/', function () use ($app) {
    $feature = file_get_contents(__DIR__ . '/../features/DisplayFeature.feature');

    return $app['twig']->render('feature.twig', [
           'feature' => $app['GherkinParser']->parseFeature($feature)
        ]
    );
});

$app->get('/features', function () use ($app) {

    return $app['twig']->render('features.twig', [
           'features' => $app['FeatureExtractor']->getFeatures()
        ]
    );
});

$app->run();

<?php
use GherkinViewer\services\FeatureExtractor;
use GherkinViewer\services\FeatureFinder;
use GherkinViewer\services\GherkinParser;

require_once __DIR__ . '/../vendor/autoload.php';

$app = new Silex\Application();

$app['config'] = [
    'featureDir' => __DIR__ . '/../features/'
];

$app->register(new Silex\Provider\TwigServiceProvider(), array(
    'twig.path' => __DIR__ . '/views',
));

$app['GherkinParser'] = function () {
    return new GherkinParser();
};

$app['FeatureExtractor'] = function () use ($app) {
    return new FeatureExtractor($app['config']['featureDir'], $app['GherkinParser']);
};

$app['FeatureFinder'] = function () use ($app) {
    return new FeatureFinder($app['config']['featureDir'], $app['GherkinParser']);
};

$app->get('/features', function () use ($app) {

    return $app['twig']->render('features.twig', [
            'features' => $app['FeatureExtractor']->getFeatures()
        ]
    );
});

$app->get('/feature/{featureTitle}', function ($featureTitle) use ($app) {

    return $app['twig']->render('feature.twig', [
            'feature' => $app['FeatureFinder']->findByTitle($featureTitle)
        ]
    );
});

$app->run();

Add feature by feature title route

Add feature by feature title route

Refactored the code slightly to share the directory variable in $app.
Removed the default / route, this can be replaced with an overview page
of some kind.


<?php
/*
 * Copyright 2013 the original author or authors.
 *
 * Licensed under the MIT License (the "License"); you may not use this
 * file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 *     http://opensource.org/licenses/MIT
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

use Vertx\Test\TestRunner;
use Vertx\Test\PhpTestCase;

/**
 * A Vert.x Net test case.
 */
class NetTestCase extends PhpTestCase {

}

TestRunner::run(new NetTestCase());

<?php
/*
 * Copyright 2013 the original author or authors.
 *
 * Licensed under the MIT License (the "License"); you may not use this
 * file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 *     http://opensource.org/licenses/MIT
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

use Vertx\Test\TestRunner;
use Vertx\Test\PhpTestCase;

/**
 * A Vert.x Net test case.
 */
class NetTestCase extends PhpTestCase {

  private $server = NULL;

  private $client = NULL;

  public function setUp() {
    $this->server = Vertx::createNetServer();
    $this->client = Vertx::createNetClient();
  }

  /**
   * Tests connecting client to server.
   */
  public function testConnect() {
    $this->server->connectHandler(function($socket) {
      $this->assertNotNull($socket);
      $this->assertNotNull($socket->localAddress);
      $this->assertNotNull($socket->remoteAddress);
    });

    $this->server->listen(8181, '0.0.0.0', function($server, $error) {
      $this->assertNull($error, 'An error was thrown on server listen.');
      $this->assertNotNull($server, 'The server was not passed to server listen handler.');
      $this->client->connect(8181, 'localhost', function($socket, $error) {
        $this->assertNull($error);
        $this->assertNotNull($socket);
        $this->assertNotNull($socket->localAddress);
        $this->assertNotNull($socket->remoteAddress);
        $this->complete();
      });
    });
  }

  public function tearDown() {
    $this->client->close();
    $this->server->close();
  }

}

TestRunner::run(new NetTestCase());

Add Net client-server connect tests.

Add Net client-server connect tests.