<?php

namespace rmatil\cms\Mail\PhpMailer;

use rmatil\cms\Exceptions\InvalidConfigurationException;
use rmatil\cms\Handler\ConfigurationHandler;
use rmatil\cms\Mail\MailInterface;
use RuntimeException;

class PhpMailer {

    const MAILER_NAME = 'php_mailer';

    /**
     * @var \PHPMailer
     */
    protected $phpMailer;

    public function __construct() {
        $config = ConfigurationHandler::readConfiguration(CONFIG_FILE);

        if (! array_key_exists('mail', $config) ||
            ! array_key_exists(PhpMailer::MAILER_NAME, $config['mail'])) {
            throw new InvalidConfigurationException(sprintf('Expected a mail configuration for %s', PhpMailer::MAILER_NAME));
        }

        $mailConfig = $config['mail'][PhpMailer::MAILER_NAME];

        $this->phpMailer = new \PHPMailer(true);
        // Set mailer to use SMTP
        $this->phpMailer->isSMTP();
        $this->phpMailer->SMTPDebug = false;
        $this->phpMailer->Debugoutput = 'html';
        // update settings
        $this->phpMailer->Host = $mailConfig['host'];
        $this->phpMailer->Username = $mailConfig['username'];
        $this->phpMailer->Password = $mailConfig['password'];
        $this->phpMailer->Port = intval($mailConfig['port']);

    }

    public function send(MailInterface $mail) {
        if ( ! ($mail instanceof PhpMailerMail)) {
            throw new RuntimeException(sprintf("Mail must be of instance %s to be sent using %s", PhpMailerMail::class, PhpMailer::class));
        }

        $receiver = $mail->getTo();

        $this->phpMailer->Subject = $mail->getSubject();
        $this->phpMailer->Body = $mail->getBody();
        $this->phpMailer->From = $mail->getFromEmail();
        $this->phpMailer->FromName = $mail->getFromName();
        $this->phpMailer->WordWrap = 50;
        $this->phpMailer->addAddress($receiver['email'], $receiver['name']);
        $this->phpMailer->addReplyTo($mail->getFromEmail(), $mail->getFromName());
        $this->phpMailer->isHTML(true);

        if ( ! $this->phpMailer->send()) {
            throw new \RuntimeException($this->phpMailer->ErrorInfo);
        }

        return true;
    }

}

<?php

namespace rmatil\cms\Mail\PhpMailer;

use rmatil\cms\Mail\AMail;

class PhpMailerMail extends AMail {

    protected $body;

    public function __construct($subject, $fromEmail, $fromName, array $to, $body) {
        $this->body = $body;
        parent::__construct($subject, $fromEmail, $fromName, $to);
    }

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

}

Fix wrong copy and paste

Fix wrong copy and paste


<?php

/*
 * This file is part of PHP-FFmpeg.
 *
 * (c) Alchemy <info@alchemy.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace FFMpeg\Coordinate;

use FFMpeg\Exception\InvalidArgumentException;

/**
 * Dimension object, used for manipulating width and height couples
 */
class Dimension
{
    private $width;
    private $height;

    /**
     * @param integer $width
     * @param integer $height
     *
     * @throws InvalidArgumentException when one of the parameteres is invalid
     */
    public function __construct($width, $height)
    {
        if ($width <= 0 || $height <= 0) {
            throw new InvalidArgumentException('Width and height should be positive integer');
        }

        $this->width = (int) $width;
        $this->height = (int) $height;
    }

    /**
     * Returns width.
     *
     * @return width
     */
    public function getWidth()
    {
        return $this->width;
    }

    /**
     * Returns height.
     *
     * @return integer
     */
    public function getHeight()
    {
        return $this->height;
    }

    /**
     * Returns the ratio.
     *
     * @param type $forceStandards Whether or not force the use of standards ratios;
     *
     * @return AspectRatio
     */
    public function getRatio($forceStandards = true)
    {
        return AspectRatio::create($this, $forceStandards);
    }
}

<?php

/*
 * This file is part of PHP-FFmpeg.
 *
 * (c) Alchemy <info@alchemy.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace FFMpeg\Coordinate;

use FFMpeg\Exception\InvalidArgumentException;

/**
 * Dimension object, used for manipulating width and height couples
 */
class Dimension
{
    private $width;
    private $height;

    /**
     * @param integer $width
     * @param integer $height
     *
     * @throws InvalidArgumentException when one of the parameteres is invalid
     */
    public function __construct($width, $height)
    {
        if ($width <= 0 || $height <= 0) {
            throw new InvalidArgumentException('Width and height should be positive integer');
        }

        $this->width = (int) $width;
        $this->height = (int) $height;
    }

    /**
     * Returns width.
     *
     * @return integer
     */
    public function getWidth()
    {
        return $this->width;
    }

    /**
     * Returns height.
     *
     * @return integer
     */
    public function getHeight()
    {
        return $this->height;
    }

    /**
     * Returns the ratio.
     *
     * @param type $forceStandards Whether or not force the use of standards ratios;
     *
     * @return AspectRatio
     */
    public function getRatio($forceStandards = true)
    {
        return AspectRatio::create($this, $forceStandards);
    }
}

Fix Doc comment (width => integer)

Fix Doc comment (width => integer)


<?php

declare(strict_types=1);

namespace League\Tactician\Handler;

use BadMethodCallException;
use League\Tactician\Exception;
use Throwable;
use function get_class;
use function gettype;
use function is_object;

/**
 * Thrown when a specific handler object can not be used on a command object.
 *
 * The most common reason is the receiving method is missing or incorrectly
 * named.
 */
final class CanNotInvokeHandler extends BadMethodCallException implements Exception
{
    /** @var object */
    private $command;

    public static function forCommand(object $command, string $reason): self
    {
        $type = \get_class($command);

        $exception = new self(
            'Could not invoke handler for command ' . $type .
            ' for reason: ' . $reason
        );
        $exception->command = $command;

        return $exception;
    }

    private function __construct(string $message = '', $code = 0, Throwable $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }

    /**
     * Returns the command that could not be invoked
     */
    public function getCommand(): object
    {
        return $this->command;
    }
}

<?php

declare(strict_types=1);

namespace League\Tactician\Handler;

use BadMethodCallException;
use League\Tactician\Exception;
use Throwable;
use function get_class;
use function gettype;
use function is_object;

/**
 * Thrown when a specific handler object can not be used on a command object.
 *
 * The most common reason is the receiving method is missing or incorrectly
 * named.
 */
final class CanNotInvokeHandler extends BadMethodCallException implements Exception
{
    /** @var object */
    private $command;

    public static function forCommand(object $command, string $reason): self
    {
        $type = \get_class($command);

        $exception = new self(
            'Could not invoke handler for command ' . $type .
            ' for reason: ' . $reason
        );
        $exception->command = $command;

        return $exception;
    }

    private function __construct(string $message = '', int $code = 0, Throwable $previous = null)
    {
        parent::__construct($message, $code, $previous);
    }

    /**
     * Returns the command that could not be invoked
     */
    public function getCommand(): object
    {
        return $this->command;
    }
}

Add missing typehint for PHPStan/PHP 7.2


<?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)
    {
        switch($provider)
        {
            case "php":
                if (!isset(self::$lprovider[$provider]))
                {
                    require_once("class.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.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;

    /**
     * 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)
    {
        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: Fix typo for requiring L10nProvider files


<?php

/*
 * This file is part of the PcdxParameterEncryptionBundle package.
 *
 * (c) picodexter <https://picodexter.io/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Picodexter\ParameterEncryptionBundle\DependencyInjection;

/**
 * ServiceNames.
 *
 * Contains names for this bundle's Symfony services that are referenced in the code.
 */
final class ServiceNames
{
    const ALGORITHM_CONFIGURATION = 'pcdx_parameter_encryption.configuration.algorithm_configuration';
    const PARAMETER_REPLACER = 'pcdx_parameter_encryption.replacement.parameter_replacer';
    const REPLACEMENT_PATTERN_ALGORITHM_PREFIX = 'pcdx_parameter_encryption.replacement.pattern.algorithm.';

    /**
     * Constructor.
     *
     * Forbid instantiation.
     */
    public function __construct()
    {
        throw new \BadMethodCallException('This class cannot be instantiated.');
    }
}

<?php

/*
 * This file is part of the PcdxParameterEncryptionBundle package.
 *
 * (c) picodexter <https://picodexter.io/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Picodexter\ParameterEncryptionBundle\DependencyInjection;

/**
 * ServiceNames.
 *
 * Contains names for this bundle's Symfony services that are referenced in the code.
 */
final class ServiceNames
{
    const ALGORITHM_CONFIGURATION = 'pcdx_parameter_encryption.configuration.algorithm_configuration';
    const ALGORITHM_PREFIX = 'pcdx_parameter_encryption.configuration.algorithm.';
    const PARAMETER_REPLACER = 'pcdx_parameter_encryption.replacement.parameter_replacer';
    const REPLACEMENT_PATTERN_ALGORITHM_PREFIX = 'pcdx_parameter_encryption.replacement.pattern.algorithm.';

    /**
     * Constructor.
     *
     * Forbid instantiation.
     */
    public function __construct()
    {
        throw new \BadMethodCallException('This class cannot be instantiated.');
    }
}

Add service name prefix for algorithms

Add service name prefix for algorithms


<?php

/*
 * Copyright 2012 Facebook, Inc.
 *
 * 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.
 */

final class PhabricatorPolicyCapability extends PhabricatorPolicyConstants {

  const CAN_VIEW        = 'view';

}

<?php

/*
 * Copyright 2012 Facebook, Inc.
 *
 * 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.
 */

final class PhabricatorPolicyCapability extends PhabricatorPolicyConstants {

  const CAN_VIEW        = 'view';
  const CAN_EDIT        = 'edit';
  const CAN_JOIN        = 'join';

}

Add "Edit" and "Join" capabilities

Add "Edit" and "Join" capabilities

Summary: These are general-purpose capabilities required by Projects.

Test Plan: Trivial.

Reviewers: vrana, btrahan

Reviewed By: vrana

CC: aran

Maniphest Tasks: T603

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


Primary Link

			<?= $page->link() ?>

All links

			<? foreach($page->links->find_all() as $link): ?>
				<li data-link="<?= $link->location ?>" data-id="<?= $link->id ?>">
					<?= $link->location ?>
					<?= Form::radio('is_primary', $link->location, (bool) $link->is_primary, array('class' => 'b-links-primary')) ?>
					<?= Form::checkbox("redirect_" . $link->id, 1, (bool) $link->redirect, array('class' => 'b-links-redirect')) ?>

			<? endforeach; ?>

Short Link

			<?= URL::site($page->short_link()) ?>

Primary Link

			<?= $page->link() ?>

All links

			<? foreach($page->links->order_by('location', 'asc')->find_all() as $link): ?>
				<li data-link="<?= $link->location ?>" data-id="<?= $link->id ?>">
					<?= $link->location ?>
					<?= Form::radio('is_primary', $link->location, (bool) $link->is_primary, array('class' => 'b-links-primary')) ?>
					<?= Form::checkbox("redirect_" . $link->id, 1, (bool) $link->redirect, array('class' => 'b-links-redirect')) ?>

			<? endforeach; ?>

Short Link

			<?= URL::site($page->short_link()) ?>

Order page links by location

Order page links by location


<?php echo '<?php' ?>

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

class CreateIndices extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('indices', function(Blueprint $table) {

            $table->increments('id');
            $table->text('params');
            $table->integer('order')->unsigned()->default(0);
            $table->string('title', 255);
            $table->string('slug', 255)->unique();
            $table->string('meta', 255);
            $table->string('namespace', 255);
            $table->text('href');
            $table->integer('disabled')->default(0);
            $table->integer('navigation')->default(0);
            $table->integer('published')->default(0);
            $table->timestamps();
        });
    }

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

<?php echo '<?php' ?>

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

class CreateIndices extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('indices', function(Blueprint $table) {

            $table->increments('id');
            $table->text('params');
            $table->integer('order')->unsigned()->default(0);
            $table->string('title', 255);
            $table->string('slug', 255)->unique();
            $table->string('namespace', 255);
            $table->text('href');
            $table->integer('disabled')->default(0);
            $table->integer('navigation')->default(0);
            $table->integer('published')->default(0);
            $table->timestamps();
        });
    }

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

Remove 'meta' in favour of 'params'

Remove 'meta' in favour of 'params'


<?php

namespace BeBat\PolyTree\Relations;

use BeBat\PolyTree\Contracts\Node;
use BeBat\PolyTree\Exceptions\Cycle as CycleException;

class HasChildren extends Direct
{
    public function __construct(Node $node)
    {
        $foreignKey = $node->getParentKeyName();
        $otherKey   = $node->getChildKeyName();

        parent::__construct($node, $foreignKey, $otherKey);
    }

    public function attach($child, array $attributes = [], $touch = true)
    {
        if (!$child instanceof Node) {
            throw new \Exception("We're not quite ready to deal with this situation yet");
        }

        $connection = $this->getBaseQuery()->getConnection();

        $connection->beginTransaction();

        parent::attach($child, $attributes, $touch);

        $descendants = $this->parent->hasDescendants();

        $descendants->unlock();
        $descendants->attach($child);
        $descendants->lock();

        $connection->commit();
    }
}

<?php

namespace BeBat\PolyTree\Relations;

use BeBat\PolyTree\Contracts\Node;
use BeBat\PolyTree\Exceptions\Cycle as CycleException;

class HasChildren extends Direct
{
    public function __construct(Node $node)
    {
        $foreignKey = $node->getParentKeyName();
        $otherKey   = $node->getChildKeyName();

        parent::__construct($node, $foreignKey, $otherKey);
    }

    public function attach($child, array $attributes = [], $touch = true)
    {
        if (!$child instanceof Node) {
            throw new \Exception("We're not quite ready to deal with this situation yet");
        }

        $connection = $this->getBaseQuery()->getConnection();

        $connection->beginTransaction();

        parent::attach($child, $attributes, $touch);

        $descendants = $this->getParent()->hasDescendants();

        $descendants->unlock();
        $descendants->attach($child);
        $descendants->lock();

        $connection->commit();
    }
}

Use getParent() allows for some easier mocking


@extends('webed-core::admin._master')

@section('css')

@endsection

@section('js')

@endsection

@section('js-init')

@endsection

@section('content')

                        Dashboard statistics

                    Comming soon!

        @php do_action('meta_boxes', 'main', 'webed-dashboard.index') @endphp

@endsection

@extends('webed-core::admin._master')

@section('css')

@endsection

@section('js')

@endsection

@section('js-init')

@endsection

@section('content')

        @php do_action('webed-dashboard.index.stat-boxes.get') @endphp

        @php do_action('webed-dashboard.index.other.get') @endphp

@endsection

Add view hook for other plugins show stats in dashboard statistics


<?php

namespace Grav\Common;

/**
 * Offers composer helper methods.
 *
 * @author  eschmar
 * @license MIT
 */
class Composer
{
    /**
     * Returns the location of composer.
     *
     * @return string
     */
    public static function getComposerLocation()
    {
        // check for global composer install
        $path = shell_exec("which composer");

        // fall back to grav bundled composer
        if (!$path || !preg_match('/(composer|composer\.phar)$/', $path)) {
            $path =  "bin/composer.phar";
        }

        return $path;
    }
}

<?php

namespace Grav\Common;

/**
 * Offers composer helper methods.
 *
 * @author  eschmar
 * @license MIT
 */
class Composer
{
    /**
     * Returns the location of composer.
     *
     * @return string
     */
    public static function getComposerLocation()
    {
        // check for global composer install
        $path = trim(shell_exec("which composer"));

        // fall back to grav bundled composer
        if (!$path || !preg_match('/(composer|composer\.phar)$/', $path)) {
            $path =  "bin/composer.phar";
        }

        return $path;
    }
}

Fix line break in command

Fix line break in command


<?php

namespace BeanstalkSatisGen\File;

class Composer extends Json
{

    /**
     * Returns whether or not this composer file is a satis package based on the
     * contents.
     *
     * @return boolean
     */
    public function isComposerPackage()
    {
        return
            ! empty($this->content) &&
            $this->hasName() &&
            (
                $this->hasPackageType() ||
                $this->isSatisPackage()
            );
    }

    /**
     * Whether or not this composer file has a name
     */
    protected function hasName()
    {
        return ! empty($this->content->name);
    }

    /**
     * Whether or not this composer.json has a type that is a package
     *
     * @return bool
     */
    protected function hasPackageType()
    {
        $allowableTypes = array(
            'library',
            'wordpress-plugin',
            'symfony-bundle',
            'drupal-module'
        );

        return isset($this->content->type) && in_array($this->content->type, $allowableTypes);
    }

    /**
     * Whether or not this composer is a satis package
     *
     * @return bool
     */
    protected function isSatisPackage()
    {
        return
            isset($this->content->extra) &&
            isset($this->content->extra->{'satis-package'}) &&
            true === $this->content->extra->{'satis-package'};
    }
}

<?php

namespace BeanstalkSatisGen\File;

class Composer extends Json
{

    /**
     * Returns whether or not this composer file is a satis package based on the
     * contents.
     *
     * @return boolean
     */
    public function isComposerPackage()
    {
        return
            ! empty($this->content) &&
            $this->hasName() &&
            (
                $this->hasPackageType() ||
                $this->isSatisPackage()
            );
    }

    /**
     * Whether or not this composer file has a name
     */
    protected function hasName()
    {
        return ! empty($this->content->name);
    }

    /**
     * Whether or not this composer.json has a type that is a package
     *
     * @return bool
     */
    protected function hasPackageType()
    {
        $allowableTypes = array(
            'library',
            'wordpress-plugin',
            'wordpress-muplugin',
            'symfony-bundle',
            'drupal-module'
        );

        return isset($this->content->type) && in_array($this->content->type, $allowableTypes);
    }

    /**
     * Whether or not this composer is a satis package
     *
     * @return bool
     */
    protected function isSatisPackage()
    {
        return
            isset($this->content->extra) &&
            isset($this->content->extra->{'satis-package'}) &&
            true === $this->content->extra->{'satis-package'};
    }
}

Add wordpress-muplugin is allowable package type


<?php

/*
 * This file is part of the VantomasWebsite package.
 *
 * (c) Thomas Juhnke <dev@van-tomas.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace DreadLabs\VantomasWebsite\Disqus\Resource;

/**
 * Resource resolver
 *
 * Use this in your application in order to resolve to proper
 * resource objects.
 *
 * @Thomas Juhnke <dev@van-tomas.de>
 */
interface ResolverInterface
{

    /**
     * Resolves a concrete resource by topic + action
     *
     * @param string $topic
     * @param string $action
     *
     * @return AbstractResource
     */
    public function resolve($topic, $action);
}

<?php

/*
 * This file is part of the VantomasWebsite package.
 *
 * (c) Thomas Juhnke <dev@van-tomas.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace DreadLabs\VantomasWebsite\Disqus\Resource;

/**
 * Resource resolver
 *
 * Use this in your application in order to resolve to proper
 * resource objects.
 *
 * @author Thomas Juhnke <dev@van-tomas.de>
 */
interface ResolverInterface
{

    /**
     * Resolves a concrete resource by topic + action
     *
     * @param string $topic
     * @param string $action
     *
     * @return AbstractResource
     */
    public function resolve($topic, $action);
}

Fix doc block author tag

[FIX] Fix doc block author tag


<?php
declare(strict_types = 1);
/**
 * /src/Request/ParamConverter/RestResourceConverter.php
 *
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */

namespace App\Request\ParamConverter;

use App\Resource\ResourceCollection;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface;
use Symfony\Component\HttpFoundation\Request;
use Throwable;

/**
 * Class RestResourceConverter
 *
 * Purpose of this param converter is to use exactly same methods and workflow as in basic REST API requests.
 *
 * @package App\Request\ParamConverter
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */
class RestResourceConverter implements ParamConverterInterface
{
    private ResourceCollection $collection;

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

    /**
     * {@inheritdoc}
     *
     * @throws Throwable
     */
    public function apply(Request $request, ParamConverter $configuration): bool
    {
        $name = $configuration->getName();
        $identifier = (string)$request->attributes->get($name, '');
        $resource = $this->collection->get($configuration->getClass());

        if ($identifier !== '') {
            $request->attributes->set($name, $resource->findOne($identifier, true));
        }

        return true;
    }

    public function supports(ParamConverter $configuration): bool
    {
        return $this->collection->has($configuration->getClass());
    }
}

<?php
declare(strict_types = 1);
/**
 * /src/Request/ParamConverter/RestResourceConverter.php
 *
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */

namespace App\Request\ParamConverter;

use App\Resource\ResourceCollection;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterInterface;
use Symfony\Component\HttpFoundation\Request;
use Throwable;

/**
 * Class RestResourceConverter
 *
 * Purpose of this param converter is to use exactly same methods and workflow
 * as in basic REST API requests.
 *
 * @package App\Request\ParamConverter
 * @author TLe, Tarmo Leppänen <tarmo.leppanen@pinja.com>
 */
class RestResourceConverter implements ParamConverterInterface
{
    public function __construct(
        private ResourceCollection $collection,
    ) {
    }

    /**
     * {@inheritdoc}
     *
     * @throws Throwable
     */
    public function apply(Request $request, ParamConverter $configuration): bool
    {
        $name = $configuration->getName();
        $identifier = (string)$request->attributes->get($name, '');
        $resource = $this->collection->get($configuration->getClass());

        if ($identifier !== '') {
            $request->attributes->set($name, $resource->findOne($identifier, true));
        }

        return true;
    }

    public function supports(ParamConverter $configuration): bool
    {
        return $this->collection->has($configuration->getClass());
    }
}

Use PHP 8 constructor property promotion


<?php

class ProjectsController extends Controller {

	public function show(Project $project)
	{
		$currentSprint = $project->currentSprint();

		return $currentSprint ? App::make('SprintsController')->show($currentSprint)
		                      : View::make('project.view', compact('project'));
	}

	public function index()
	{
		return View::make('project.index')->with('projects', Project::all());
	}

	public function store()
	{
		$title = Input::get('title');
		$project = new Project([
			'title' => $title,
			'slug' => Str::slug($title)
		]);
		$validation = $project->validate();

		if ($validation->fails())
		{
			foreach ($validation->messages()->all() as $error)
			{
				Flash::error($error);
			}
		} elseif ($project->save())
		{
			Flash::success('Successfully created the new project');
		} else
		{
			Flash::error('Could not create the project. Please try again');
		}

		return Redirect::back();
	}

	public function update(Project $project)
	{
		$project->update(Input::all());

		return Redirect::back();
	}
}

<?php

class ProjectsController extends Controller {

	public function show(Project $project)
	{
		$currentSprint = $project->currentSprint();

		return $currentSprint ? App::make('SprintsController')->show($currentSprint)
		                      : View::make('project.view', compact('project'));
	}

	public function index()
	{
		return View::make('project.index')->with('projects', Project::all());
	}

	public function store()
	{
		$title = Input::get('title');
		$project = new Project([
			'title' => $title,
			'slug' => Str::slug($title)
		]);
		$validation = $project->validate();

		if ($validation->fails())
		{
			foreach ($validation->messages()->all() as $error)
			{
				Flash::error($error);
			}
		} elseif ($project->save())
		{
			Flash::success('Successfully created the new project');
		} else
		{
			Flash::error('Could not create the project. Please try again');
		}

		return Redirect::back();
	}

	public function update(Project $project)
	{
		$project->update(Input::all());

		Flash::success('The project settings have been updated');
		return Redirect::back();
	}
}

Add success message for saving project settings.


<?php

/*
 * This file is part of the Carbon package.
 *
 * (c) Brian Nesbitt <brian@nesbot.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Tests\Carbon;

use Carbon\Carbon;
use Tests\AbstractTestCase;

class NowDerivativesTest extends AbstractTestCase
{
    public function testNowWithSameTimezone()
    {
        $dt = Carbon::now('Europe/London');
        $dt2 = $dt->nowWithSameTz();
        $this->assertSame($dt2->toDateTimeString(), $dt->toDateTimeString());
        $this->assertSame($dt2->tzName, $dt->tzName);
    }

    public function testResolveCarbon()
    {
        $dt = Carbon::now();
        $dt2 = Carbon::yesterday();
        $this->assertInstanceOfCarbon($dt->resolveCarbon($dt2));
        $this->assertSame($dt2, $dt->resolveCarbon($dt2));
    }

    public function testResolveCarbonNull()
    {
        $dt = Carbon::now();
        $this->assertInstanceOfCarbon($dt->resolveCarbon(null));
        $this->assertSame($dt->toDateTimeString(), $dt->resolveCarbon(null)->toDateTimeString());
    }
}

<?php

/*
 * This file is part of the Carbon package.
 *
 * (c) Brian Nesbitt <brian@nesbot.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Tests\Carbon;

use Carbon\Carbon;
use Tests\AbstractTestCase;

class NowDerivativesTest extends AbstractTestCase
{
    public function testNowWithSameTimezone()
    {
        $dt = Carbon::now('Europe/London');
        $dt2 = $dt->nowWithSameTz();

        $this->assertSame($dt2->toDateTimeString(), $dt->toDateTimeString());
        $this->assertSame($dt2->tzName, $dt->tzName);

        Carbon::setTestNow(new Carbon('2017-07-29T07:57:27.123456Z'));
        $dt = Carbon::createFromTime(13, 40, 00, 'Africa/Asmara');
        $dt2 = $dt->nowWithSameTz();
        Carbon::setTestNow();

        $this->assertSame($dt->format('H:i'), '13:40');
        $this->assertSame($dt2->format('H:i'), '10:57');
        $this->assertSame($dt2->tzName, $dt->tzName);
    }
}

Remove resolveCarbon tests and add test for nowWithSameTz


@extends('layout.layout')

@section('content')

{{ trans('general.titles.forgotten-link') }}

                {{ trans('general.texts.forgotten-link') }}

            <form class="ui form">

                    <input type="text" name="email" placeholder="{{ trans('general.placeholders.forgotten-link-mail') }}">

                    <button class="ui red submit button" type="submit">{{ trans('general.buttons.submit.send-short') }}</button>

            </form>

@stop

Remove newlines & old TODO

Remove newlines &  old TODO


<?php

class MWEchoDbFactoryTest extends MediaWikiTestCase {

	public function testNewFromDefault() {
		$db = MWEchoDbFactory::newFromDefault();
		$this->assertInstanceOf( 'MWEchoDbFactory', $db );

		return $db;
	}

	/**
	 * @depends testNewFromDefault
	 */
	public function testGetEchoDb( MWEchoDbFactory $db ) {
		$this->assertInstanceOf( 'DatabaseBase', $db->getEchoDb( DB_MASTER ) );
		$this->assertInstanceOf( 'DatabaseBase', $db->getEchoDb( DB_REPLICA ) );
	}

	/**
	 * @depends testNewFromDefault
	 */
	public function testGetLB( MWEchoDbFactory $db ) {
		$reflection = new ReflectionClass( 'MWEchoDbFactory' );
		$method = $reflection->getMethod( 'getLB' );
		$method->setAccessible( true );
		$this->assertInstanceOf( 'LoadBalancer', $method->invoke( $db ) );
	}

}

<?php

use Wikimedia\Rdbms\IDatabase;
use Wikimedia\Rdbms\ILoadBalancer;

class MWEchoDbFactoryTest extends MediaWikiTestCase {

	public function testNewFromDefault() {
		$db = MWEchoDbFactory::newFromDefault();
		$this->assertInstanceOf( 'MWEchoDbFactory', $db );

		return $db;
	}

	/**
	 * @depends testNewFromDefault
	 */
	public function testGetEchoDb( MWEchoDbFactory $db ) {
		$this->assertInstanceOf( IDatabase::class, $db->getEchoDb( DB_MASTER ) );
		$this->assertInstanceOf( IDatabase::class, $db->getEchoDb( DB_REPLICA ) );
	}

	/**
	 * @depends testNewFromDefault
	 */
	public function testGetLB( MWEchoDbFactory $db ) {
		$reflection = new ReflectionClass( 'MWEchoDbFactory' );
		$method = $reflection->getMethod( 'getLB' );
		$method->setAccessible( true );
		$this->assertInstanceOf( ILoadBalancer::class, $method->invoke( $db ) );
	}

}

Check for IDatabase (not DatabaseBase) in tests

Change-Id: Ia94fcae2a1dd28761b4e2f40fa1491f8401ad491


<?php namespace App\Modules\Auth\Http\Controllers;

use View, Sentinel, Input, Session, Redirect, FrontController;

class LogoutController extends FrontController {

    public function getIndex()
    {
        Sentinel::logout();

        $this->alertInfo(trans('auth::logged_out'));
    }
}

<?php namespace App\Modules\Auth\Http\Controllers;

use View, Sentinel, Input, Session, Redirect, FrontController;

class LogoutController extends FrontController {

    public function getIndex()
    {
        Sentinel::logout();

        $this->alertFlash(trans('auth::logged_out'));

        return redirect('/');
    }
}

Use flash message instead of static message and redirect to the landing page


<?php

namespace EWZ\Bundle\RecaptchaBundle\Factory;

use EWZ\Bundle\RecaptchaBundle\Form\Type\EWZRecaptchaType;
use EWZ\Bundle\RecaptchaBundle\Validator\Constraints\IsTrue;
use Symfony\Component\Form\FormFactoryInterface;

class EWZRecaptchaV2FormBuilderFactory
{
    private $builder;

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

    public function get()
    {
        return $this->builder->createBuilder(EWZRecaptchaType::class, null, [
                'constraints' => array(
                    new IsTrue(),
                ),
            ]);
    }
}

<?php

namespace EWZ\Bundle\RecaptchaBundle\Factory;

use EWZ\Bundle\RecaptchaBundle\Form\Type\EWZRecaptchaType;
use EWZ\Bundle\RecaptchaBundle\Validator\Constraints\IsTrue;
use Symfony\Component\Form\FormFactoryInterface;

class EWZRecaptchaV2FormBuilderFactory
{
    private $builder;

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

    public function get(array $options = array())
    {
        $constraint = array(
            'constraints' => array(
                new IsTrue(),
            ),
        );

        return $this->builder->createBuilder(EWZRecaptchaType::class, null, array_merge($options, $constraint));
    }
}

Use v2 service with options

Use v2 service with options


<?php

namespace Deployer;

// Read more on https://github.com/sourcebroker/deployer-extended#deploy-check-composer-install
task('deploy:check_composer_install', function () {
    if (file_exists(get('current_dir') . '/composer.lock')) {
        $output = runLocally('{{local/bin/composer}} --ignore-platform-reqs install --dry-run 2>&1');
        if (strpos($output, 'Nothing to install') === false) {
            throw new \Exception('A composer.lock changes has been detected but you did not run "composer install". Please run composer install, then check if everything is working on your instance and do deploy after.');
        }
    }
})->desc('Check if composer install is needed before making deployment');

<?php

namespace Deployer;

// Read more on https://github.com/sourcebroker/deployer-extended#deploy-check-composer-install
task('deploy:check_composer_install', function () {
    if (file_exists(get('current_dir') . '/composer.lock')) {
        $output = runLocally('{{local/bin/composer}} --ignore-platform-reqs install --dry-run 2>&1');
        if (strpos($output, 'Nothing to install') === false && strpos($output, 'Package operations: 0 installs, 0 updates, 0 removals') === false) {
            throw new \Exception('A composer.lock changes has been detected but you did not run "composer install". Please run composer install, then check if everything is working on your instance and do deploy after.');
        }
    }
})->desc('Check if composer install is needed before making deployment');

[BUGFIX] Fix check if composer install must be run because of composer.lock changes.


<?php

use App\Models\Draw;
use App\Models\PendingDraw;
use App\Models\Participant;
use App\Notifications\PendingDraw as PendingDrawNotification;
use Illuminate\Notifications\AnonymousNotifiable;

it('can create pending draws (and just pending ones)', function ($participants) {
    Notification::fake();

    assertModelCount(PendingDraw::class, 0);

    createDraw($participants)
        ->assertSuccessful();

    assertModelCount(PendingDraw::class, 1);

    assertModelCount(Draw::class, 0);
    assertModelCount(Participant::class, 0);

    $draw = PendingDraw::find(1);

    Notification::assertSentTo(
        new AnonymousNotifiable,
        PendingDrawNotification::class,
        function ($notification, $channels, $notifiable) use ($draw) {
            return $notifiable->routes['mail'] === [['name' => $draw->organizer_name, 'email' => $draw->organizer_email]];
        }
    );
})->with('participants list');

it('respects limit in participants count', function ($participants) {
    Notification::fake();

    config()->set('app.participants_limit', count($participants) - 1);

    createDraw($participants)
        ->assertUnprocessable()
        ->assertJsonValidationErrors([
            'participants'
        ]);

    config()->set('app.participants_limit', count($participants));

    createDraw($participants)
        ->assertSuccessful();
})->with('participants list');

it('handles no limit in participants count', function ($participants) {
    Notification::fake();

    config()->set('app.participants_limit', null);

    createDraw($participants)
        ->assertSuccessful();
})->with('participants list');

Add test for participants limit disabled


<?php
	require_once('IP2Country.php');

	define('DB_SERVER', 'localhost');
	define('DB_PORT', 3306);
	define('DB_NAME', 'dnscheckng');
	define('DB_USER', 'dnscheckng');
	define('DB_PASS', 'dnscheckng');

	define('STATUS_OK', 'OK');
	define('STATUS_WARN', 'WARNING');
	define('STATUS_ERROR', 'ERROR');
	define('STATUS_DOMAIN_DOES_NOT_EXIST', 'ERROR_DOMAIN_DOES_NOT_EXIST');
	define('STATUS_DOMAIN_SYNTAX', 'ERROR_DOMAIN_SYNTAX');
	define('STATUS_NO_NAMESERVERS', 'ERROR_NO_NAMESERVERS');
	define('STATUS_IN_PROGRESS', 'IN_PROGRESS');
	define('STATUS_INTERNAL_ERROR', 'INTERNAL_ERROR');

	define('PAGER_SIZE', 10);

	define('GUI_TIMEOUT', 300);

	$sourceIdentifiers = array(
		'standard' => 'webgui',
		'undelegated' => 'webgui-undelegated'
	);

	define('DEFAULT_LANGUAGE_ID', getDefaultLanguage());

    /* Provide a place where settings can be overridden, to make Debian packaging easier. */
    if (is_readable('/etc/dnscheck.php')) {
        require_once('/etc/dnscheck.php');
    }

?>

<?php
	require_once('IP2Country.php');

	define('DB_SERVER', 'localhost');
	define('DB_PORT', 3306);
	define('DB_NAME', 'dnscheckng');
	define('DB_USER', 'dnscheckng');
	define('DB_PASS', 'dnscheckng');

	define('STATUS_OK', 'OK');
	define('STATUS_WARN', 'WARNING');
	define('STATUS_ERROR', 'ERROR');
	define('STATUS_DOMAIN_DOES_NOT_EXIST', 'ERROR_DOMAIN_DOES_NOT_EXIST');
	define('STATUS_DOMAIN_SYNTAX', 'ERROR_DOMAIN_SYNTAX');
	define('STATUS_NO_NAMESERVERS', 'ERROR_NO_NAMESERVERS');
	define('STATUS_IN_PROGRESS', 'IN_PROGRESS');
	define('STATUS_INTERNAL_ERROR', 'INTERNAL_ERROR');

	define('PAGER_SIZE', 10);

	define('GUI_TIMEOUT', 300);

	$sourceIdentifiers = array(
		'standard' => 'webgui',
		'undelegated' => 'webgui-undelegated'
	);

	define('DEFAULT_LANGUAGE_ID', getDefaultLanguage());

    /* Provide a place where settings can be overridden, to make Debian packaging easier. */
    if (is_readable('/etc/dnscheck/webui_config.php')) {
        require_once('/etc/dnscheck/webui_config.php');
    }

?>

Move webui optional config file to the same directory DNSCheck Lib uses.


<?php

function Assets_after_Community_create($params)
{
	$userId = $params['userId'];
	$community = $params['community'];
	$skipAccess = $params['skipAccess'];

	if ($skipAccess || Q::ifset($params, 'isSuperAdmin', false)) {
		return;
	}

	$amountToSpend = (int)Q_Config::expect('Assets', 'credits', 'amounts', 'createCommunity');

	Assets_Credits::spend($amountToSpend, $userId, array(
		'reason' => "Created community ".$community->id,
		'publisherId' => $community->id,
		'streamName' => 'Streams/experience/main'
	));
}

<?php

function Assets_after_Community_create($params)
{
	$userId = $params['userId'];
	$community = $params['community'];
	$skipAccess = $params['skipAccess'];
	$quota = $params['quota'];

	// if for some reason skippAccess or quota not exceeded
	if ($skipAccess || $quota instanceof Users_Quota) {
		return;
	}

	$amountToSpend = (int)Q_Config::expect('Assets', 'credits', 'amounts', 'createCommunity');

	Assets_Credits::spend($amountToSpend, $userId, array(
		'reason' => "Created community ".$community->id,
		'publisherId' => $community->id,
		'streamName' => 'Streams/experience/main'
	));
}

Check quota when spend credits for new community. If quota not exceeded, don't charge credits.


<?php
namespace DexBarrett\ClockworkSms\Test;

use DexBarrett\ClockworkSms\Client;
use DexBarrett\ClockworkSms\Exception\ClockworkSmsException;

class ClientTest extends \PHPUnit_Framework_TestCase
{

    public function test_it_fails_if_no_apikey_is_provided()
    {
        $this->expectException(ClockworkSmsException::class);

        $client = new Client();
    }

    public function test_it_parses_options()
    {
        $this->markTestIncomplete(
          'This test has not been implemented yet.'
        );
    }

    public function test_throws_error_when_trying_to_get_invalid_option()
    {
        $this->expectException(ClockworkSmsException::class);

        $client = new Client('APIKEY');
        $client->getOptionValue('foo');
    }
}

<?php
namespace DexBarrett\ClockworkSms\Test;

use DexBarrett\ClockworkSms\Client;
use DexBarrett\ClockworkSms\Exception\ClockworkSmsException;

class ClientTest extends \PHPUnit_Framework_TestCase
{

    public function test_it_fails_if_no_apikey_is_provided()
    {
        $this->expectException(ClockworkSmsException::class);

        $client = new Client();
    }

    public function test_it_overrides_provided_options()
    {
        $client = new Client('APIKEY', ['ssl' => true, 'log' => true]);
        $this->assertEquals($client->getOptionValue('ssl'), true);
        $this->assertEquals($client->getOptionValue('log'), true);
    }

    public function test_throws_error_when_trying_to_get_invalid_option()
    {
        $this->expectException(ClockworkSmsException::class);

        $client = new Client('APIKEY');
        $client->getOptionValue('foo');
    }

    public function test_ignores_invalid_options_provided()
    {
        $this->expectException(ClockworkSmsException::class);

        $client = new Client('APIKEY', ['log' => true, 'foo' => 'bar']);
        $client->getOptionValue('foo');
    }
}

Add tests for parsing options

Add tests for parsing options


<?php

namespace Neblion\ScrumBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DefaultControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();
        $crawler = $client->request('GET', '/');
        $this->assertTrue($crawler->filter('html:contains("Dashboard")')->count() == 0);
        $this->assertTrue($crawler->filter('html:contains("Hello, world!")')->count() == 1);
    }
}

<?php

namespace Neblion\ScrumBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DefaultControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();
        $crawler = $client->request('GET', '/');
        $this->assertTrue($crawler->filter('html:contains("Dashboard")')->count() == 0);
        $this->assertTrue($crawler->filter('html:contains("Hello, world!")')->count() == 1);
    }

    public function testProjects()
    {
        $client = static::createClient();
        $crawler = $client->request('GET', '/projects');
        $this->assertTrue($client->getResponse()->isRedirect());
    }
}

Add functionnal test in DefautController


<?php namespace Spekkionu\Assetcachebuster;

use Illuminate\Support\ServiceProvider;

class AssetcachebusterServiceProvider extends ServiceProvider
{

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

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

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app['assetcachebuster'] = $this->app->share(function ($app) {
            $options['enable'] = $this->app['config']->get('assetcachebuster::enable');
            $options['hash'] = $this->app['config']->get('assetcachebuster::hash');
            $options['cdn'] = $this->app['config']->get('assetcachebuster::cdn');
            $options['prefix'] = $this->app['config']->get('assetcachebuster::prefix');
            return new Assetcachebuster($options);
        });

        // Register artisan command
        $this->app['command.assetcachebuster.generate'] = $this->app->share(
            function ($app) {
                return new Console\GenerateCommand($app['files']);
            }
        );
        $this->commands(
            'command.assetcachebuster.generate'
        );
    }

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

<?php namespace Spekkionu\Assetcachebuster;

use Illuminate\Support\ServiceProvider;

class AssetcachebusterServiceProvider extends ServiceProvider
{

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

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

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app['assetcachebuster'] = $this->app->share(function ($app) {
            $options['enable'] = $app['config']->get('assetcachebuster::enable');
            $options['hash'] = $app['config']->get('assetcachebuster::hash');
            $options['cdn'] = $app['config']->get('assetcachebuster::cdn');
            $options['prefix'] = $app['config']->get('assetcachebuster::prefix');
            return new Assetcachebuster($options);
        });

        // Register artisan command
        $this->app['command.assetcachebuster.generate'] = $this->app->share(
            function ($app) {
                return new Console\GenerateCommand($app['files']);
            }
        );
        $this->commands(
            'command.assetcachebuster.generate'
        );
    }

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

Fix package service provider registration


<?php

// Path to the front controller (this file)
define('FCPATH', __DIR__.DIRECTORY_SEPARATOR);

// Location of the Paths config file.
// This is the first of two lines that might need to be changed, depending on your folder structure.
$pathsPath = FCPATH . '../application/Config/Paths.php';

/*
 *---------------------------------------------------------------
 * BOOTSTRAP THE APPLICATION
 *---------------------------------------------------------------
 * This process sets up the path constants, loads and registers
 * our autoloader, along with Composer's, loads our constants
 * and fires up an environment-specific bootstrapping.
 */

// Ensure the current directory is pointing to the front controller's directory
chdir(__DIR__);

// Load our paths config file
require $pathsPath;
$paths = new Config\Paths();

// Location of the framework bootstrap file.
// This is the second of two lines that might need to be changed, depending on your folder structure.
$app = require FCPATH . '../system/bootstrap.php';

/*
 *---------------------------------------------------------------
 * LAUNCH THE APPLICATION
 *---------------------------------------------------------------
 * Now that everything is setup, it's time to actually fire
 * up the engines and make this app do it's thang.
 */
$app->run();

<?php

// Path to the front controller (this file)
define('FCPATH', __DIR__.DIRECTORY_SEPARATOR);

// Location of the Paths config file.
// This is the first of two lines that might need to be changed, depending on your folder structure.
$pathsPath = FCPATH . '../application/Config/Paths.php';

/*
 *---------------------------------------------------------------
 * BOOTSTRAP THE APPLICATION
 *---------------------------------------------------------------
 * This process sets up the path constants, loads and registers
 * our autoloader, along with Composer's, loads our constants
 * and fires up an environment-specific bootstrapping.
 */

// Ensure the current directory is pointing to the front controller's directory
chdir(__DIR__);

// Load our paths config file
require $pathsPath;
$paths = new Config\Paths();

// Location of the framework bootstrap file.
// This is the second of two lines that might need to be changed, depending on your folder structure.
$app = require FCPATH . '../system/bootstrap.php';

/*
 *---------------------------------------------------------------
 * LAUNCH THE APPLICATION
 *---------------------------------------------------------------
 * Now that everything is setup, it's time to actually fire
 * up the engines and make this app do its thang.
 */
$app->run();

Fix grammar in front controller comment.


<?php

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

class CreateUsersTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('users', function(Blueprint $table)
		{
			$table->increments('id');
			$table->string('fullname');
			$table->string('username');
			$table->string('email');
			$table->string('password');
			$table->timestamps();
		});
	}

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

}

<?php

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

class CreateUsersTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('admins', function(Blueprint $table)
		{
			$table->increments('id');
			$table->string('fullname');
			$table->string('username');
			$table->string('email');
			$table->string('password');
			$table->timestamps();
		});
	}

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

}

Fix merge conflicts and add new features


<?php

namespace App;

use Fenos\Notifynder\Notifable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Silber\Bouncer\Database\HasRolesAndAbilities;

class User extends Authenticatable
{
    use HasRolesAndAbilities, Notifable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];
}

<?php

namespace App;

use Fenos\Notifynder\Notifable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Silber\Bouncer\Database\HasRolesAndAbilities;

/**
 * @property mixed id,       The record id in the database. (auto-increment)
 * @property mixed name,     The name from the user.
 * @property mixed gsm,      The gsm number from the user.
 * @property mixed email,    The email address from the user.
 * @property mixed password, The password from the user.
 */
class User extends Authenticatable
{
    use HasRolesAndAbilities, Notifable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['name', 'email', 'password'];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];
}

Add properties to the user models

Add properties to the user models


<?php
// TrainingMatrix Copyright 2014 by WebIS Spring 2014 License Apache 2.0
namespace WCS;
require_once 'Work-Cell-Scheduler/Config/global.php';

class TrainingMatrix{

	private $people = array('Ann','Bob','Clide');
	private $line = array(1010,1020,1030,1040);

	public function getPeople() {
		// $people=array('Dr.Middelkoop','JD');
		$db = new \mysqli(\WCS\Config::$dbhost,\WCS\Config::$dbuser,\WCS\Config::$dbpassword,'database');
		if($db===NULL){
			echo "Error unable to connect to database";
			exit();
		}
		$stmt=$db->prepare("SELECT person FROM TrainingMatrix");
		if($stmt===FALSE){
			echo "prepare error ",$db->error;
			exit();
		}
		$stmt->execute();
		$stmt->bind_result($person);
		$people=array();
		while($stmt->fetch()){
			$people[]=$person;
		}
		return $people;
	}

	public function getWorkstations() {
		return $this->line;
	}

	public function getTraining($person,$workstation){
		return 0.10;
	}

}

?>

<?php
// TrainingMatrix Copyright 2014 by WebIS Spring 2014 License Apache 2.0
namespace WCS;
require_once 'Work-Cell-Scheduler/Config/global.php';

class TrainingMatrix{

	private $people = array('Ann','Bob','Clide');
	private $line = array(1010,1020,1030,1040);

	public function getPeople() {
		// $people=array('Dr.Middelkoop','JD');
		$db = new \mysqli(\WCS\Config::$dbhost,\WCS\Config::$dbuser,\WCS\Config::$dbpassword,'database');
		if($db===NULL){
			echo "Error unable to connect to database";
			exit();
		}
		$stmt=$db->prepare("SELECT person FROM TrainingMatrix");
		if($stmt===FALSE){
			echo "prepare error ",$db->error;
			exit();
		}
		$stmt->execute();
		if($stmt===FALSE){
			echo "prepare error ",$db->error;
			exit();
		}
		$stmt->bind_result($person);
		if($stmt===FALSE){
			echo "prepare error ",$db->error;
			exit();
		}
		$people=array();
		while($stmt->fetch()){
			$people[]=$person;
		}
		return $people;
	}

	public function getWorkstations() {
		return $this->line;
	}

	public function getTraining($person,$workstation){
		return 0.10;
	}

}

?>

Add tests to make sure code succeeds.

Add tests to make sure code succeeds.


    @guest

Login

Register

    @else

            user()->name }}" />

            Logout

    @endguest

    @guest

Login

Register

    @else

            user()->name }}" />

            {{ auth()->user()->name }}

            Logout

    @endguest

Add userpage's link to user menu

Add userpage's link to user menu


<?php

namespace MCordingley\LaravelSapient\Test\Middleware;

use Illuminate\Http\Request;
use MCordingley\LaravelSapient\Test\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    /**
     * @return Request
     */
    final protected static function createRequest(): Request
    {
        $parameters = '';
        $parsed = [];
        parse_str($parameters, $parsed);

        return Request::create('/foo', 'POST', $parsed, [], [], [], $parameters);
    }
}

<?php

namespace MCordingley\LaravelSapient\Test\Middleware;

use Illuminate\Http\Request;
use MCordingley\LaravelSapient\Test\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    /**
     * @return Request
     */
    final protected static function createRequest(): Request
    {
        $parameters = 'foo=1&joy=2&test=bar';
        $parsed = [];
        parse_str($parameters, $parsed);

        return Request::create('/foo', 'POST', $parsed, [], [], [], $parameters);
    }
}

Add some data to the test request object.


<?php

namespace App\Http\Controllers;

use App\Http\Request;
use App\Http\Resources\ConfigResource;
use App\Model\Config;

class SettingsController extends Controller
{
    public function index()
    {
        return response()->format([
            'html' => view('settings.index', [
                'configs' => Config::unlocked()->get(),
            ]),
            'json' => ConfigResource::collection(Config::unlocked()->get()),
        ]);
    }

    public function update(Request $request)
    {
        $settings = $request->get('settings');
        foreach ($settings as $name => $value) {
            Config::where('locked', false)
                ->where('name', $name)
                ->update(['value' => $value]);
        }

        return response()->format([
            'html' => redirect(route('settings.index'))->with('success', 'Settings updated'),
            'json' => ConfigResource::collection(Config::unlocked()->get()),
        ]);
    }
}

<?php

namespace App\Http\Controllers;

use App\Http\Request;
use App\Http\Resources\ConfigResource;
use App\Model\Config;

class SettingsController extends Controller
{
    public function index()
    {
        return response()->format([
            'html' => view('settings.index', [
                'configs' => Config::unlocked()->get(),
            ]),
            'json' => ConfigResource::collection(Config::unlocked()->get()),
        ]);
    }

    public function update(Request $request)
    {
        $settings = $request->get('settings');
        foreach ($settings as $name => $value) {
            Config::unlocked()
                ->where('name', $name)
                ->update(['value' => $value]);
        }

        return response()->format([
            'html' => redirect(route('settings.index'))->with('success', 'Settings updated'),
            'json' => ConfigResource::collection(Config::unlocked()->get()),
        ]);
    }
}

Use scope instead of condition in query

Use scope instead of condition in query


<?php

declare(strict_types=1);

namespace Doctrine\Migrations\Version;

use Doctrine\Migrations\Configuration\Configuration;

/**
 * The Factory class is responsible for creating instances of the Version class for a version number
 * and a migration class name.
 *
 * @var internal
 */
class Factory
{
    /** @var Configuration */
    private $configuration;

    /** @var ExecutorInterface */
    private $versionExecutor;

    public function __construct(Configuration $configuration, ExecutorInterface $versionExecutor)
    {
        $this->configuration   = $configuration;
        $this->versionExecutor = $versionExecutor;
    }

    public function createVersion(string $version, string $migrationClassName): Version
    {
        return new Version(
            $this->configuration,
            $version,
            $migrationClassName,
            $this->versionExecutor
        );
    }
}

<?php

declare(strict_types=1);

namespace Doctrine\Migrations\Version;

use Doctrine\Migrations\Configuration\Configuration;

/**
 * The Factory class is responsible for creating instances of the Version class for a version number
 * and a migration class name.
 *
 * @internal
 */
class Factory
{
    /** @var Configuration */
    private $configuration;

    /** @var ExecutorInterface */
    private $versionExecutor;

    public function __construct(Configuration $configuration, ExecutorInterface $versionExecutor)
    {
        $this->configuration   = $configuration;
        $this->versionExecutor = $versionExecutor;
    }

    public function createVersion(string $version, string $migrationClassName): Version
    {
        return new Version(
            $this->configuration,
            $version,
            $migrationClassName,
            $this->versionExecutor
        );
    }
}

Use correct syntax to mark class as internal

@var internal looks like a mistake


<?php
namespace Config;
class Modules {
    private $environment;

    public function __construct($modules = [], $configFile = "config.json") {
        $this->modules = $modules;
        $this->configFile = $configFile;
    }

    public function getModuleSettings() {
        $moduleSettings = [];
        foreach ($this->modules as $moduleName) {
            $moduleFile = 'Modules/' . $moduleName . '/' . $this->configFile;
            if ($settings = $this->getFile($moduleFile)) $moduleSettings[] = $settings;
        }
        return $moduleSettings;
    }

    private function getFile($file) {
        if (!file_exists($file)) return false;

        $settings = json_decode(str_replace('{dir}', dirname($file), file_get_contents($file)), true);
        if (isset($settings['extend'])) {
            $settings = array_merge($this->getFile($settings['extend']), $settings);
        }
        return $settings;
    }
}

<?php
namespace Config;
class Modules {
    private $environment;

    public function __construct($modules = [], $configFile = "config.json") {
        $this->modules = $modules;
        $this->configFile = $configFile;
    }

    public function getModuleSettings() {
        $moduleSettings = [];
        foreach ($this->modules as $moduleName) {
            $moduleFile = 'Modules/' . $moduleName . '/' . $this->configFile;
            if ($settings = $this->getFile($moduleFile)) $moduleSettings[] = $settings;
        }
        return $moduleSettings;
    }

    private function getFile($file) {
        $fileName = __DIR__ . '/../' . $file;
        if (!file_exists($fileName)) return false;

        $settings = json_decode(str_replace('{dir}', dirname($file), file_get_contents($fileName)), true);
        if (isset($settings['extend'])) {
            $settings = array_merge($this->getFile($settings['extend']), $settings);
        }
        return $settings;

    }
}

Fix bug with loading Module config file

Fix bug with loading Module config file


<?php
class Kwc_Advanced_CommunityVideo_Controller extends Kwf_Controller_Action_Auto_Kwc_Form
{
    protected $_formName = 'Kwc_Advanced_CommunityVideo_Form';
}

<?php
class Kwc_Advanced_CommunityVideo_Controller extends Kwf_Controller_Action_Auto_Kwc_Form
{
}

Remove formName for easier overwriting

Remove formName for easier overwriting


<?php
/**
 * This file is part of the Imbo package
 *
 * (c) Christer Edvartsen <cogo@starzinger.net>
 *
 * For the full copyright and license information, please view the LICENSE file that was
 * distributed with this source code.
 */

namespace ImboBehatFeatureContext\DatabaseTest;

use ImboBehatFeatureContext\AdapterTest;
use Imbo\Database\Doctrine as Database;
use PDO;

/**
 * Class for suites that want to use the Doctrine database adapter with a SQLite database
 *
 * @author Christer Edvartsen <cogo@starzinger.net>
 */
class DoctrineSQLite implements AdapterTest {
    /**
     * {@inheritdoc}
     */
    static public function setUp(array $config) {
        $path = tempnam(sys_get_temp_dir(), 'imbo_behat_test_database_doctrine_sqlite');

        // Create tmp tables
        $pdo = new PDO(sprintf('sqlite:%s', $path));

        $sqlStatementsFile = sprintf('%s/setup/doctrine.sqlite.sql', $config['project_root']);

        array_map(function($query) use ($pdo) {
            $pdo->query($query);
        }, explode("\n\n", file_get_contents($sqlStatementsFile)));

        return ['path' => $path];
    }

    /**
     * {@inheritdoc}
     */
    static public function tearDown(array $config) {
        unlink($config['path']);
    }

    /**
     * {@inheritdoc}
     */
    static public function getAdapter(array $config) {
        return new Database([
            'path' => $config['path'],
            'driver' => 'pdo_sqlite',
        ]);
    }
}

<?php
/**
 * This file is part of the Imbo package
 *
 * (c) Christer Edvartsen <cogo@starzinger.net>
 *
 * For the full copyright and license information, please view the LICENSE file that was
 * distributed with this source code.
 */

namespace ImboBehatFeatureContext\DatabaseTest;

use ImboBehatFeatureContext\AdapterTest;
use Imbo\Database\Doctrine as Database;
use PDO;

/**
 * Class for suites that want to use the Doctrine database adapter with a SQLite database
 *
 * @author Christer Edvartsen <cogo@starzinger.net>
 */
class DoctrineSQLite implements AdapterTest {
    /**
     * {@inheritdoc}
     */
    static public function setUp(array $config) {
        $path = tempnam(sys_get_temp_dir(), 'imbo_behat_test_database_doctrine_sqlite');

        // Create tmp tables
        $pdo = new PDO(sprintf('sqlite:%s', $path));

        $sqlStatementsFile = sprintf('%s/setup/doctrine.sqlite.sql', $config['project_root']);
        $pdo->exec(file_get_contents($sqlStatementsFile));

        return ['path' => $path];
    }

    /**
     * {@inheritdoc}
     */
    static public function tearDown(array $config) {
        unlink($config['path']);
    }

    /**
     * {@inheritdoc}
     */
    static public function getAdapter(array $config) {
        return new Database([
            'path' => $config['path'],
            'driver' => 'pdo_sqlite',
        ]);
    }
}

Use ->exec for generating the test SQL database from setup/


<?php

/*
 * This file is part of the Sonata Project package.
 *
 * (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Sonata\CoreBundle\Model;

if (interface_exists(\Sonata\Doctrine\Model\PageableManagerInterface::class, false)) {
    @trigger_error(
        'The '.__NAMESPACE__.'\PageableManagerInterface class is deprecated since version 3.x and will be removed in 4.0.'
        .' Use Sonata\DatagridBundle\Pager\PageableInterface instead.',
        E_USER_DEPRECATED
    );
}

class_alias(
    \Sonata\Doctrine\Model\PageableManagerInterface::class,
    __NAMESPACE__.'\PageableManagerInterface'
);

if (false) {
    interface PageableManagerInterface extends \Sonata\Doctrine\Model\PageableManagerInterface
    {
    }
}

Add missing trick to appear in the classmap

This should have been part of 9a3d73acfcac1104c33cda810eedfedea2a7b7ba


<?php

namespace Laratrust\Traits;

/**
 * This file is part of Laratrust,
 * a role & permission management solution for Laravel.
 *
 * @license MIT
 * @package Laratrust
 */

use Illuminate\Support\Facades\Config;

trait LaratrustPermissionTrait
{
    /**
     * Many-to-Many relations with role model.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function roles()
    {
        return $this->belongsToMany(
            Config::get('laratrust.role'),
            Config::get('laratrust.permission_role_table')
        );
    }

    /**
     * Boot the permission model
     * Attach event listener to remove the many-to-many records when trying to delete
     * Will NOT delete any records if the permission model uses soft deletes.
     *
     * @return void|bool
     */
    public static function bootLaratrustPermissionTrait()
    {
        static::deleting(function ($permission) {
            if (!method_exists(Config::get('laratrust.permission'), 'bootSoftDeletes')) {
                $permission->roles()->sync([]);
            }

            return true;
        });
    }
}

<?php

namespace Laratrust\Traits;

/**
 * This file is part of Laratrust,
 * a role & permission management solution for Laravel.
 *
 * @license MIT
 * @package Laratrust
 */

use Illuminate\Support\Facades\Config;

trait LaratrustPermissionTrait
{
    /**
     * Many-to-Many relations with role model.
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function roles()
    {
        return $this->belongsToMany(
            Config::get('laratrust.role'),
            Config::get('laratrust.permission_role_table'),
            Config::get('laratrust.permission_foreign_key'),
            Config::get('laratrust.role_foreign_key')
        );
    }

    /**
     * Boot the permission model
     * Attach event listener to remove the many-to-many records when trying to delete
     * Will NOT delete any records if the permission model uses soft deletes.
     *
     * @return void|bool
     */
    public static function bootLaratrustPermissionTrait()
    {
        static::deleting(function ($permission) {
            if (!method_exists(Config::get('laratrust.permission'), 'bootSoftDeletes')) {
                $permission->roles()->sync([]);
            }

            return true;
        });
    }
}

Add fk to pivot relationship

Add fk to pivot relationship

There are config values for foreign keys in pivot tables,
but they are not used in declaration of relationship. Fix it.


<?php
/*=========================================================================

  Program:   CDash - Cross-Platform Dashboard System
  Module:    $Id$
  Language:  PHP
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Kitware, Inc.  All rights reserved.
  See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

// To be able to access files in this CDash installation regardless
// of getcwd() value:
//
$cdashpath = str_replace('\\', '/', dirname(dirname(__FILE__)));
set_include_path($cdashpath . PATH_SEPARATOR . get_include_path());

require_once("cdash/pdo.php");

// Add other api includes here
require("api_coverage.php");
require("api_project.php");
require("api_build.php");
require("api_user.php");

if(!isset($_GET['method']))
  {
  echo "Method should be set: method=...";
  return;
  }
$method = $_GET['method'];

$classname = ucfirst($method).'API';
$class = new $classname;
$class->Parameters = $_GET;
$results = $class->Run();

// Return json by default
echo json_encode($results);
?>

<?php
/*=========================================================================

  Program:   CDash - Cross-Platform Dashboard System
  Module:    $Id$
  Language:  PHP
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Kitware, Inc.  All rights reserved.
  See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

// To be able to access files in this CDash installation regardless
// of getcwd() value:
//
$cdashpath = str_replace('\\', '/', dirname(dirname(__FILE__)));
set_include_path($cdashpath . PATH_SEPARATOR . get_include_path());

require_once("cdash/pdo.php");

// Add other api includes here
require("api_coverage.php");
require("api_project.php");
require("api_build.php");
require("api_user.php");

if(!isset($_GET['method']))
  {
  echo "Method should be set: method=...";
  return;
  }
$method = $_GET['method'];

$classname = ucfirst($method).'API';
$class = new $classname;
$class->Parameters = array_merge($_GET, $_POST);
$results = $class->Run();

// Return json by default
echo json_encode($results);
?>

ENH: Allow web API parameters to be passed as POST parameters in addition to the normal GET parameters

git-svn-id: 496ab2bd9c9a782235c11388890d59de1024c1f0@2808 91079597-3006-4846-9bd3-4f3fb3d139a7


<?php namespace Illuminate\Config;

use Illuminate\Filesystem\Filesystem;

class FileEnvironmentVariablesLoader implements EnvironmentVariablesLoaderInterface {

	/**
	 * The filesystem instance.
	 *
	 * @var \Illuminate\Filesystem\Filesystem
	 */
	protected $files;

	/**
	 * The path to the configuration files.
	 *
	 * @var string
	 */
	protected $path;

	/**
	 * Create a new file environment loader instance.
	 *
	 * @param  \Illuminate\Filesystem\Filesystem  $files
	 * @return void
	 */
	public function __construct(Filesystem $files, $path = null)
	{
		$this->files = $files;
		$this->path = $path ?: base_path();
	}

	/**
	 * Load the environment variables for the given environment.
	 *
	 * @param  string  $environment
	 * @return array
	 */
	public function load($environment = null)
	{
		if ($environment == 'production') $environment = null;

		if ( ! $this->files->exists($path = $this->getFile($environment)))
		{
			return array();
		}
		else
		{
			return $this->files->getRequire($path);
		}
	}

	/**
	 * Get the file for the given environment.
	 *
	 * @param  string  $environment
	 * @return string
	 */
	protected function getFile($environment)
	{
		if ($environment)
		{
			return $this->path.'/.env.'.$environment.'.php';
		}
		else
		{
			return $this->path.'/.env.php';
		}
	}

}

<?php namespace Illuminate\Config;

use Illuminate\Filesystem\Filesystem;

class FileEnvironmentVariablesLoader implements EnvironmentVariablesLoaderInterface {

	/**
	 * The filesystem instance.
	 *
	 * @var \Illuminate\Filesystem\Filesystem
	 */
	protected $files;

	/**
	 * The path to the configuration files.
	 *
	 * @var string
	 */
	protected $path;

	/**
	 * Create a new file environment loader instance.
	 *
	 * @param  \Illuminate\Filesystem\Filesystem  $files
	 * @return void
	 */
	public function __construct(Filesystem $files, $path = null)
	{
		$this->files = $files;
		$this->path = $path ?: base_path();
	}

	/**
	 * Load the environment variables for the given environment.
	 *
	 * @param  string  $environment
	 * @return array
	 */
	public function load($environment = null)
	{
		if ($environment == 'production') $environment = null;

		if ( ! $this->files->exists($path = $this->getFile($environment)))
		{
			return array();
		}
		else
		{
			return array_dot($this->files->getRequire($path));
		}
	}

	/**
	 * Get the file for the given environment.
	 *
	 * @param  string  $environment
	 * @return string
	 */
	protected function getFile($environment)
	{
		if ($environment)
		{
			return $this->path.'/.env.'.$environment.'.php';
		}
		else
		{
			return $this->path.'/.env.php';
		}
	}

}

Load environment variables array in dot-flatten form


<?php

namespace ModHelper;

/**
 * This file deals with some database internals.
 *
 * @package ModHelper
 * @since 1.0
 */
class Database
{
	/**
	 * Handler to SMF's database functions.
	 *
	 * @example ModHelper\Database::query('', 'SELECT * FROM smf_themes', array());
	 * @param string $name The name (or key) of the $smcFunc you are calling.
	 * @param string $arguments This is an array of all arguments passed to the method.
	 * @return mixed The $smcFunc return value or false if not found.
	 * @since 3.0
	 * @version 3.0
	 */
	public static function __callStatic($name, $arguments)
	{
		global $smcFunc;
		if (isset($smcFunc[$name = 'db_' . $name])) {
			return call_user_func_array($smcFunc[$name], $arguments);
		}

		return false;
	}
}

?>

<?php

namespace ModHelper;

/**
 * This file deals with some database internals.
 *
 * @package ModHelper
 * @since 1.0
 */
class Database
{
	use Singleton;

	private $db;

	/**
	 * Handler to ElkArte's database functions.
	 *
	 * @example ModHelper\Database::query('', 'SELECT * FROM smf_themes', array());
	 * @param string $name The name (or key) of the $smcFunc you are calling.
	 * @param string $arguments This is an array of all arguments passed to the method.
	 * @return mixed The $db return value or false if not found.
	 * @since 3.0
	 * @version 3.0
	 */
	public static function __callStatic($name, $arguments)
	{
		return call_user_func_array([$db, $name], $arguments);
	}

	public function init()
	{
		$db = database();
	}
}

?>

Make the database wrapper a singleton

Make the database  wrapper a singleton


<?php

/*
 * This file is part of the OverblogThriftBundle package.
 *
 * (c) Overblog <http://github.com/overblog/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Overblog\ThriftBundle;

use Overblog\ThriftBundle\DependencyInjection\Compiler\FactoryPass;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * Overblog Thrift Bundle.
 *
 * @author Xavier HAUSHERR
 */
class OverblogThriftBundle extends Bundle
{
    /**
     * Builds the bundle.
     *
     * It is only ever called once when the cache is empty.
     *
     * This method can be overridden to register compilation passes,
     * other extensions, ...
     *
     * @param ContainerBuilder $container A ContainerBuilder instance
     */
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        $container->addCompilerPass(new FactoryPass(), PassConfig::TYPE_BEFORE_REMOVING);
    }
}

<?php

/*
 * This file is part of the OverblogThriftBundle package.
 *
 * (c) Overblog <http://github.com/overblog/>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Overblog\ThriftBundle;

use Overblog\ThriftBundle\DependencyInjection\Compiler\FactoryPass;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * Overblog Thrift Bundle.
 *
 * @author Xavier HAUSHERR
 */
class OverblogThriftBundle extends Bundle
{
    /**
     * Builds the bundle.
     *
     * It is only ever called once when the cache is empty.
     *
     * This method can be overridden to register compilation passes,
     * other extensions, ...
     *
     * @param ContainerBuilder $container A ContainerBuilder instance
     */
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        $container->addCompilerPass(new FactoryPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 1000)
    }
}

Move backward on FactoryPass type

Move backward on FactoryPass type


@extends('templates.base')

@section('title')
    {{{ substr($category->title, 0, 30) }}}
@stop

@section('body')

{{{ $category->title }}} {{ count($posts) }} {{ count($posts) === 1 ? 'post' : 'posts' }}

{{{ $category->description }}}

        @include('templates.postlist')

@stop

Add spacing to posts count

Add spacing to posts count


<!DOCTYPE html>
<html class="bg-white antialiased" lang="en">
<head>
    @include('components.meta')

    <title>@include('components.head-title')</title>

    <link rel="icon" type="image/x-icon" href="https://wayne.edu/favicon.ico">
    <link rel="stylesheet" href="{{ mix('_resources/css/main.css') }}">
    <link href="https://fonts.googleapis.com/css?family=Lato:400,700" rel="stylesheet" type="text/css">
    @if(!empty($page['canonical']))<link rel="canonical" href="{{ $page['canonical'] }}">@endif

    @include('components.ga')
</head>
<body class="font-sans font-normal text-black leading-normal text-base">

@include('components.skip')

@include('components.header')

@if(!empty($site))
    @include('components.menu-top', ['site' => $site])
@endif

@if(!empty($banner))
    @include('components.banner', ['banner' => $banner])
@endif

<main id="panel" tabindex="-1">
    @yield('content-area')
</main>

@if(!empty($social))
    @include('components.footer-social', ['social' => $social])
@endif

@if(!empty($contact))
    @include('components.footer-contact', ['contact' => $contact])
@endif

@include('components.footer')

<script src="{{ mix('_resources/js/main.js') }}"></script>
</body>
</html>

<!DOCTYPE html>
<html class="bg-white antialiased" lang="en">
<head>
    @include('components.meta')

    <title>@include('components.head-title')</title>

    <link rel="icon" type="image/x-icon" href="https://wayne.edu/favicon.ico">
    <link rel="stylesheet" href="{{ mix('_resources/css/main.css') }}">
    <link href="https://fonts.googleapis.com/css?family=Lato:400,700" rel="stylesheet" type="text/css">
    @if(!empty($page['canonical']))<link rel="canonical" href="{{ $page['canonical'] }}">@endif

    @include('components.ga')
</head>
<body class="font-sans font-normal text-black leading-normal text-base">

@include('components.skip')

@include('components.header')

@if(!empty($site))
    @include('components.menu-top', ['site' => $site])
@endif

@if(!empty($banner))
    @include('components.banner', ['banner' => $banner])
@endif

<main id="panel">
    @yield('content-area')
</main>

@if(!empty($social))
    @include('components.footer-social', ['social' => $social])
@endif

@if(!empty($contact))
    @include('components.footer-contact', ['contact' => $contact])
@endif

@include('components.footer')

<script src="{{ mix('_resources/js/main.js') }}"></script>
</body>
</html>

Add tabindex to the content landmark to make it focusable. Remove it from the previous landmark that we were trying to skip to.


<?php

namespace Mapbender\DigitizerBundle\Element\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class DigitizerAdminType extends AbstractType
{

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'application' => null
        ));
    }

    /**
     * @inheritdoc
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('target', 'Mapbender\CoreBundle\Element\Type\TargetElementType', array(
                'element_class' => 'Mapbender\CoreBundle\Element\Map',
                'application'   => $options['application'],
                'required'      => false,
                // dummy property path required for compatibility for TargetElementType
                // on Mapbender <=3.0.8.4 (no longer required on 3.0.8.5 RC and higher)
                'property_path' => '[target]',
            ))
            ->add('displayOnInactive','checkbox',array('required' => false, 'label' => 'mb.digitizer.displayOnInactive'))
            ->add('schemes', 'Mapbender\ManagerBundle\Form\Type\YAMLConfigurationType', array(
                'required' => false,
                'attr' => array(
                    'class' => 'code-yaml',
                ),
            ))
        ;
    }
}

<?php

namespace Mapbender\DigitizerBundle\Element\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class DigitizerAdminType extends AbstractType
{

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'application' => null
        ));
    }

    /**
     * @inheritdoc
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('target', 'Mapbender\CoreBundle\Element\Type\TargetElementType', array(
                'element_class' => 'Mapbender\CoreBundle\Element\Map',
                'application'   => $options['application'],
                'required'      => false,
                // dummy property path required for compatibility for TargetElementType
                // on Mapbender <=3.0.8.4 (no longer required on 3.0.8.5 RC and higher)
                'property_path' => '[target]',
            ))

            ->add('displayOnInactive', 'Symfony\Component\Form\Extension\Core\Type\CheckboxType' ,array(
                'required' => false,
                'label' => 'mb.digitizer.displayOnInactive',
            ))
            ->add('schemes', 'Mapbender\ManagerBundle\Form\Type\YAMLConfigurationType', array(
                'required' => false,
                'attr' => array(
                    'class' => 'code-yaml',
                ),
            ))
        ;
    }
}

Fix Symfony 3 incompatible form type

Fix Symfony 3 incompatible form type


<?php

namespace Nitrapi\Services\Voiceservers;

class VoiceserverDetails
{
    protected $data;

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

    public function getIP() {
        return (string)$this->data['ip'];
    }

    public function getPort() {
        return (int)$this->data['port'];
    }

    public function getSlots() {
        return (int)$this->data['slots'];
    }
}

<?php

namespace Nitrapi\Services\Voiceservers;

class VoiceserverDetails
{
    protected $data;

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

    public function getType() {
        return (string)$this->data['type'];
    }

    public function getIP() {
        return (string)$this->data['ip'];
    }

    public function isStarted() {
        return (bool)$this->data['started'];
    }

    public function isStopped() {
        return !$this->$this->isStarted();
    }

    public function getPort() {
        return (int)$this->data['port'];
    }

    public function getSlots() {
        return (int)$this->data['slots'];
    }
}

Update Wed Mar 2 13:31:00 CET 2016

Update Wed Mar  2 13:31:00 CET 2016


<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Users';
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

        <?= Html::a('Create User', ['create'], ['class' => 'btn btn-success']) ?>

    <?=
        GridView::widget([
            'dataProvider' => $dataProvider,
            'columns' => [
                'user_id',
                'user_name',
                'user_email:email',
                'user_birthday',
                ['class' => 'yii\grid\ActionColumn'],
                array(
                    'format'  =>  'image',
                    'attribute' => 'user_name',
                    'value'=>function($data){
                        return $data->user_name;
                    }
                )
            ]
        ]);
    ?>

<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Users';
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

        <?= Html::a('Create User', ['create'], ['class' => 'btn btn-success']) ?>

    <?=
        GridView::widget([
            'dataProvider' => $dataProvider,
            'columns' => [
                'user_id',
                'user_name',
                'user_email:email',
                'user_birthday',
                ['class' => 'yii\grid\ActionColumn'],
                array(
                    'format'  =>  'html',
                    'attribute' => 'user_name',
                    'value'=>function($data){
                        return $data->user_name;
                    }
                )
            ]
        ]);
    ?>

Update format type in View Index User

Update format type in View Index User


<?php

namespace Schuppo\PasswordStrength;

class PasswordStrength
{
    public function validateLetters($value)
    {
        return preg_match('/\pL/', $value);
    }

    public function validateNumbers($value)
    {
        return preg_match('/\pN/', $value);
    }

    public function validateCaseDiff($value)
    {
        return preg_match('/(\p{Ll}+.*\p{Lu})|(\p{Lu}+.*\p{Ll})/u', $value);
    }

    public function validateSymbols($value)
    {
        return preg_match('/[!@#$%^&*?()\-_=+{};:,<.>\/]/', $value);
    }
}

<?php

namespace Schuppo\PasswordStrength;

class PasswordStrength
{
    public function validateLetters($value)
    {
        return preg_match('/\pL/', $value);
    }

    public function validateNumbers($value)
    {
        return preg_match('/\pN/', $value);
    }

    public function validateCaseDiff($value)
    {
        return preg_match('/(\p{Ll}+.*\p{Lu})|(\p{Lu}+.*\p{Ll})/u', $value);
    }

    public function validateSymbols($value)
    {
        return preg_match('/[!@#$%^&*?()\-_=+{};:,<.>\/\\\]/', $value);
    }
}

Add backslash to symbols regex

Add backslash to symbols regex

Similar to the slash symbol the backslash has been missing in the symbol regex


<?php

namespace Dami\Cli\Command;

use Symfony\Component\Console\Command\Command,
    Symfony\Component\Console\Input\InputOption,
    Symfony\Component\Console\Input\InputInterface,
    Symfony\Component\Console\Output\OutputInterface;

class AbstractCommand extends Command
{
    protected function configure()
    {
        $this
            ->addOption('env', null, InputOption::VALUE_REQUIRED, 'Set environment');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $environment = $input->getOption('env');
        if (null !== $environment) {
            $config = $this->getContainer()->get('connection_config');
            $config->changeEnvironment($environment);
        }
    }
}

<?php

namespace Dami\Cli\Command;

use Symfony\Component\Console\Command\Command,
    Symfony\Component\Console\Input\InputOption,
    Symfony\Component\Console\Input\InputInterface,
    Symfony\Component\Console\Output\OutputInterface;

class AbstractCommand extends Command
{
    protected function configure()
    {
        $this
            ->addOption('env', null, InputOption::VALUE_REQUIRED, 'Set environment');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $environment = $input->getOption('env');
        if (null !== $environment) {
            $config = $this->getContainer()->get('connection_config');
            $config->changeEnvironment($environment);
        }

        $migrationDirectory = $this->getContainer()->getparameter('dami.migrations_directory');
        if (!file_exists($migrationDirectory)) {
            mkdir($migrationDirectory);
        }
    }
}

Create migration directory if not exist

Create migration directory if not exist


<?php

// Require the extension's composer autoload file. This will enable all of our
// classes in the src directory to be autoloaded.
require 'vendor/autoload.php';

// Register our service provider with the Flarum application. In here we can
// register bindings and execute code when the application boots.
$app->register('Flarum\Categories\CategoriesServiceProvider');

<?php

// Require the extension's composer autoload file. This will enable all of our
// classes in the src directory to be autoloaded.
require 'vendor/autoload.php';

// Register our service provider with the Flarum application. In here we can
// register bindings and execute code when the application boots.
return $app->register('Flarum\Categories\CategoriesServiceProvider');

Return the provider so core can store a reference to it


<?php

namespace Kunstmaan\DashboardBundle\Widget;

use Doctrine\Common\Annotations\AnnotationReader;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\DependencyInjection\ContainerInterface;

class DashboardWidget
{

    /**
     * @var ContainerAwareCommand $collector
     */
    private $command;

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

    /**
     * @param string $command
     * @param string $controller
     * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
     */
    function __construct($command, $controller, ContainerInterface $container)
    {
        $this->command = new $command();
        $this->command->setContainer($container);
        $this->controller = $controller;
    }

    /**
     * @return ContainerAwareCommand
     */
    public function getCommand()
    {
        return $this->command;
    }

    public function resolvedController()
    {
        $annotationReader = new AnnotationReader();
        $reflectionMethod = new \ReflectionMethod($this->controller, 'widgetAction');
        $methodAnnotations = $annotationReader->getMethodAnnotations($reflectionMethod);
        foreach ($methodAnnotations as $annotation) {
            if ($annotation instanceof Route) {
                if (empty($annotation)) {
                    throw new \Exception("The name is not configured in the annotation");
                }
                /** @var \Sensio\Bundle\FrameworkExtraBundle\Configuration\Route $annotation */
                return $annotation->getName();
            }
        }
        throw new \Exception("There is no route annotation");
    }
}

<?php

namespace Kunstmaan\DashboardBundle\Widget;

use Doctrine\Common\Annotations\AnnotationReader;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\DependencyInjection\ContainerInterface;

class DashboardWidget
{

    /**
     * @var ContainerAwareCommand $collector
     */
    private $command;

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

    /**
     * @param string $command
     * @param string $controller
     * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
     */
    public function __construct($command, $controller, ContainerInterface $container)
    {
        $this->command = new $command();
        $this->command->setContainer($container);
        $this->controller = $controller;
    }

    /**
     * @return ContainerAwareCommand
     */
    public function getCommand()
    {
        return $this->command;
    }

    public function resolvedController()
    {
        $annotationReader = new AnnotationReader();
        $reflectionMethod = new \ReflectionMethod($this->controller, 'widgetAction');
        $methodAnnotations = $annotationReader->getMethodAnnotations($reflectionMethod);
        foreach ($methodAnnotations as $annotation) {
            if ($annotation instanceof Route) {
                if (empty($annotation)) {
                    throw new \Exception("The name is not configured in the annotation");
                }
                /** @var \Sensio\Bundle\FrameworkExtraBundle\Configuration\Route $annotation */
                return $annotation->getName();
            }
        }
        throw new \Exception("There is no route annotation");
    }
}

Add public visibility to constructors

Add public visibility to constructors


<?php
// Set content type to XML
header('Content-type: text/xml');

// Disable any caching with HTTP headers
// Any date in the past will do here
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');

// Set always modified
// for HTTP/1.1
header('Cache-Control: no-cache, must-revalidate max-age=0');
// for HTTP/1.0
header('Pragma: no-cache');

echo $this->response;

?>

<?php
// Set content type to XML
header('Content-type: text/xml; charset=UTF-8');

// Disable any caching with HTTP headers
// Any date in the past will do here
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');

// Set always modified
// for HTTP/1.1
header('Cache-Control: no-cache, must-revalidate max-age=0');
// for HTTP/1.0
header('Pragma: no-cache');

echo $this->response;

?>

Send XML_-RPC responses in UTF-8

Send XML_-RPC responses in UTF-8

svn commit r10953