<?php

namespace Backend\Modules\MediaLibrary\Domain\MediaGroup;

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

class SingleMediaGroupType extends MediaGroupType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        parent::buildForm($builder, $options);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        parent::configureOptions($resolver);

        $resolver->setDefault('minimum_items', 1);
        $resolver->setDefault('maximum_items', 1);
    }
}

<?php

namespace Backend\Modules\MediaLibrary\Domain\MediaGroup;

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

final class SingleMediaGroupType extends MediaGroupType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        parent::buildForm($builder, $options);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        parent::configureOptions($resolver);

        $resolver->setDefault('minimum_items', 1);
        $resolver->setDefault('maximum_items', 1);
    }
}

Make the single media group type final

Make the single media group type final


<?php

namespace Knp\RadBundle\DataFixtures\ORM;

use Knp\RadBundle\DataFixtures\AbstractFixture;
use Symfony\Component\Finder\Finder;
use Doctrine\Common\Persistence\ObjectManager;
use Nelmio\Alice\Fixtures;

class LoadAliceFixtures extends AbstractFixture
{
    public function load(ObjectManager $manager)
    {
        $bundles = $this->container->getParameter('kernel.bundles');
        if (!isset($bundles['App'])) {
            return;
        }

        $refl = new \ReflectionClass($bundles['App']);
        if (class_exists($refl->getNamespaceName().'\\DataFixtures\\ORM\\LoadAliceFixtures')) {
            return;
        }

        $path = dirname($refl->getFileName()).DIRECTORY_SEPARATOR.'Resources'.
            DIRECTORY_SEPARATOR.'fixtures'.DIRECTORY_SEPARATOR.'orm';

        foreach ($this->getAliceFiles($path) as $file) {
            Fixtures::load($file, $manager, $this->getAliceOptions());
        }
    }

    protected function getAliceFiles($path)
    {
        if (!is_dir($path)) {
            return array();
        }

        return Finder::create()->files()->name('*.yml')->in($path);
    }

    protected function getAliceOptions()
    {
        return array('providers' => array($this));
    }
}

<?php

namespace Knp\RadBundle\DataFixtures\ORM;

use Knp\RadBundle\DataFixtures\AbstractFixture;

use Symfony\Component\Finder\Finder;

use Doctrine\Common\Persistence\ObjectManager;

use Nelmio\Alice\Fixtures;

class LoadAliceFixtures extends AbstractFixture
{
    public function load(ObjectManager $manager)
    {
        $env     = $this->continaer->getParameter('kernel.environment');
        $bundles = $this->container->getParameter('kernel.bundles');
        if (!isset($bundles['App'])) {
            return;
        }

        $refl = new \ReflectionClass($bundles['App']);
        if (class_exists($refl->getNamespaceName().'\\DataFixtures\\ORM\\LoadAliceFixtures')) {
            return;
        }

        $path = dirname($refl->getFileName()).DIRECTORY_SEPARATOR.'Resources'.
            DIRECTORY_SEPARATOR.'fixtures'.DIRECTORY_SEPARATOR.'orm';

        foreach ($this->getAliceFiles($path, $env) as $file) {
            Fixtures::load($file, $manager, $this->getAliceOptions());
        }
    }

    protected function getAliceFiles($path, $environment)
    {
        $paths = array();
        if (is_dir($path)) {
            $paths[] = $path;
        }
        if (is_dir($path.DIRECTORY_SEPARATOR.$environment)) {
            $paths[] = $path.DIRECTORY_SEPARATOR.$environment;
        }

        if (0 == count($paths)) {
            return array();
        }

        return Finder::create()
            ->files()
            ->name('*.yml')
            ->depth(1)
            ->sortByName()
            ->in($paths)
        ;
    }

    protected function getAliceOptions()
    {
        return array('providers' => array($this));
    }
}

Add environment support and tuneup Finder


<!DOCTYPE html>

		<meta charset="utf-8">

		<title>Pet Foster ABQ - Persona-B</title>

Pet Foster ABQ

It is 6:05 p.m. and Chloe is using her families desk top to search for a site that will help her locate placement for the dog. As she only has a short time before she must stop using the internet and do her homework, she dismissed sites that seem to complicated. She is looking for a site that displays relevant information and instructions that are clearly displayed and easy to access.

<!DOCTYPE html>

		<meta charset="utf-8">

		<title>Pet Foster ABQ - Persona-B</title>

Pet Foster ABQ

It is 6:05 p.m. and Chloe, with the help of her father, is using her families desk top to search for a site that will help her locate placement for the dog. As she only has a short time before she must stop using the internet and do her homework, she dismissed sites that seem to complicated. She is looking for a site that displays relevant information and instructions that are clearly displayed and easy to access, she comes across Pet Adopt ABQ

User goes to Foster website.

Page Loads landing page.

User selects post pet for adoption

Page prompts user to sign in to post a pet.

User creates an account and verifies through email

Page delivers description fields and pet info for user to enter

User enters information in form page such as animal size and breed.

Page prompts user to enter a picture of pet

User uploads pet image and submits

Page delivers confirmation and lets user know they will be contacted via email when an adopter is found.

		</ol

Use Case for persona b (pet seeker)

Use Case for persona b (pet seeker)


<?php

	namespace MikeVrind\Deployer\Controllers;

	use Illuminate\Console\Command;
	use MikeVrind\Deployer\Deployer;

class DeployCommand extends Command
{
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'deployer:deploy';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Manually execute the deplot commands without a webhook';

	/**
	 * Holds in instance of the actual Deployer
	 *
	 * @var Deployer
	 */
	protected $deployer;

	/**
	 * @param Deployer $deployer
	 */
	public function __construct(Deployer $deployer)
	{
		$this->deployer = $deployer;

		parent::__construct();
	}

	/**
	 * Execute the deployer
	 *
	 * @return void
	 */
	public function fire()
	{

		if ( $this->confirm('Do you wish to manually run the deployer commands? [y|N]'))
		{

			if( $this->deployer->deploy() )
			{
				$this->info('Deployment successful');
			}
			else
			{
				$this->error($this->deployer->getErrorMessage());
			}

		}

	}

}

<?php

	namespace MikeVrind\Deployer\Controllers;

	use Illuminate\Console\Command;
	use MikeVrind\Deployer\Deployer;

	class DeployCommand extends Command
	{
		/**
		 * The name and signature of the console command.
		 *
		 * @var string
		 */
		protected $signature = 'deployer:deploy';

		/**
		 * The console command description.
		 *
		 * @var string
		 */
		protected $description = 'Manually execute the deploy commands without a webhook';

		/**
		 * Holds in instance of the actual Deployer
		 *
		 * @var Deployer
		 */
		protected $deployer;

		/**
		 * @param Deployer $deployer
		 */
		public function __construct( Deployer $deployer )
		{
			$this->deployer = $deployer;

			parent::__construct();
		}

		/**
		 * Execute the deployer
		 *
		 * @return void
		 */
		public function fire()
		{

			if( $this->confirm( 'Do you wish to manually run the deployer commands? [y|N]' ) )
			{

				if( $this->deployer->deploy() )
				{
					$this->info( 'Deployment successful' );
				}
				else
				{
					$this->error( $this->deployer->getErrorMessage() );
				}

			}

		}

	}

Fix formatting and typo in docblock

Fix formatting and typo in docblock


<?php
    abstract class ActiveRecordBase {
        public function delete() {
            $id = $this->id;
            db_delete(
                $this->tableName,
                compact( "id" )
            );
        }

        public function save() {
            $this->validate();
            if ( $this->exists ) {
                $this->update();
            }
            else {
                $this->create();
            }
        }
    }

    class ModelNotFoundException extends Exception {
        public function __construct() {
            parent::__construct( 'NotFound' );
        }
    }

    class ModelValidationException extends Exception {
        public $error;

        public function __construct( $error = "" ) {
            parent::__construct( "Model validation error: " . $error );
            $this->error = $error;
        }
    }
?>

<?php
    abstract class ActiveRecordBase {
        public function delete() {
            $id = $this->id;
            db_delete(
                $this->tableName,
                compact( "id" )
            );
        }

        public function save() {
            $this->validate();
            if ( $this->exists ) {
                $this->update();
            }
            else {
                $this->create();
            }
        }
    }

    class ModelNotFoundException extends Exception {
        public function __construct() {
            parent::__construct( 'Model not found' );
        }
    }

    class ModelValidationException extends Exception {
        public $error;

        public function __construct( $error = "" ) {
            parent::__construct( "Model validation error: " . $error );
            $this->error = $error;
        }
    }
?>

Add a more descriptive message at ModelNotFoundException


<?php

/**
 * This bootstrap file is the real starting point for the application.
 *
 * It is required from the public index.php, and is used as the backbone of the application.
 * Every request starts and ends in this file.
 */

define("PROJECT_ROOT", realpath(getcwd() . "/../"));

# Include FastRouter #

require_once PROJECT_ROOT . "lib/FastRouter/src/bootstrap.php";

$dispatcher = FastRoute\simpleDispatcher(function(\FastRoute\RouteCollector $r) {
    //@Todo: Add rules here. Some examples follow
    $r->addRoute('GET', '/user/{name}/{id:[0-9]+}', 'handler0');
    $r->addRoute('GET', '/user/{id:[0-9]+}', 'handler1');
    $r->addRoute('GET', '/user/{name}', 'handler2');
});

$requestMethod = isset($_SERVER["REQUEST_METHOD"]) ? $_SERVER["REQUEST_METHOD"] : "GET";
$uri = isset($_SERVER["REQUEST_URI"]) ? $_SERVER["REQUEST_URI"] : "/";

$routeInfo = $dispatcher->dispatch($requestMethod, $uri);

switch ($routeInfo[0]) {
    case \FastRoute\Dispatcher::NOT_FOUND:
        //@Todo: Implement 404 page!
        break;
    case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
        //@Todo: Implement 405 page!
        break;
    case \FastRoute\Dispatcher::FOUND:
        $handler = $routeInfo[1];
        $vars = $routeInfo[2];
        //@Todo: Do stuff with $handler and $vars.
    break;
}

<?php

/**
 * This bootstrap file is the real starting point for the application.
 *
 * It is required from the public index.php, and is used as the backbone of the application.
 * Every request starts and ends in this file.
 */

define("PROJECT_ROOT", realpath(getcwd() . "/../"));

# Include FastRouter #

require_once PROJECT_ROOT . "/lib/FastRouter/src/bootstrap.php";

$dispatcher = FastRoute\simpleDispatcher(function(\FastRoute\RouteCollector $r) {
    //@Todo: Add rules here. Some examples follow
    $r->addRoute('GET', '/user/{name}/{id:[0-9]+}', 'handler0');
    $r->addRoute('GET', '/user/{id:[0-9]+}', 'handler1');
    $r->addRoute('GET', '/user/{name}', 'handler2');
});

$requestMethod = isset($_SERVER["REQUEST_METHOD"]) ? $_SERVER["REQUEST_METHOD"] : "GET";
$uri = isset($_SERVER["REQUEST_URI"]) ? $_SERVER["REQUEST_URI"] : "/";

$routeInfo = $dispatcher->dispatch($requestMethod, $uri);

switch ($routeInfo[0]) {
    case \FastRoute\Dispatcher::NOT_FOUND:
        //@Todo: Implement 404 page!
        break;
    case \FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
        //@Todo: Implement 405 page!
        break;
    case \FastRoute\Dispatcher::FOUND:
        $handler = $routeInfo[1];
        $vars = $routeInfo[2];
        //@Todo: Do stuff with $handler and $vars.
    break;
}

Fix bug with inclusion path.

Fix bug with inclusion path.


<?php namespace App;

use App\Data\Favorite;

trait Favoritable
{
	public function favorites()
	{
		return $this->morphMany(Favorite::class, 'favorited');
	}

	public function getFavoritesCountAttribute()
	{
		return $this->favorites->count();
	}

	public function favorite()
	{
		$attributes = ['user_id' => auth()->id()];

		if (! $this->favorites()->where($attributes)->exists()) {
			return $this->favorites()->create($attributes);
		}
	}

	public function isFavorited()
	{
		return !! $this->favorites->where('user_id', auth()->id())->count();
	}
}

<?php namespace App;

use App\Data\Favorite;

trait Favoritable
{
	protected static function bootFavoritable()
	{
		static::deleting(function ($model) {
			$model->favorites->each->delete();
		});
	}

	public function favorites()
	{
		return $this->morphMany(Favorite::class, 'favorited');
	}

	public function getFavoritesCountAttribute()
	{
		return $this->favorites->count();
	}

	public function favorite()
	{
		$attributes = ['user_id' => auth()->id()];

		if (! $this->favorites()->where($attributes)->exists()) {
			return $this->favorites()->create($attributes);
		}
	}

	public function isFavorited()
	{
		return !! $this->favorites->where('user_id', auth()->id())->count();
	}

	public function getIsFavoritedAttribute()
	{
		return $this->isFavorited();
	}

	public function unfavorite()
	{
		$attributes = ['user_id' => auth()->id()];

		$this->favorites()->where($attributes)->get()->each->delete();
	}
}

Fix some issues with favorites

Fix some issues with favorites


<?php

namespace Bauhaus;

use Bauhaus\Container\ItemNotFoundException;

class Container implements ContainerInterface
{
    private $items = [];

    public function __construct(array $items = [])
    {
        $this->items = $items;
    }

    final public function has($label)
    {
        return array_key_exists($label, $this->items);
    }

    public function get($label)
    {
        if (false === $this->has($label)) {
            throw new ItemNotFoundException($label);
        }

        return $this->items[$label];
    }

    final public function __get($label)
    {
        return $this->get($label);
    }

    final public function items(): array
    {
        return $this->items;
    }

    public function asArray(): array
    {
        throw new \RuntimeException('Method asArray not implemented');
    }
}

<?php

namespace Bauhaus;

use Bauhaus\Container\ItemNotFoundException;

class Container implements ContainerInterface
{
    private $items = [];

    public function __construct(array $items = [])
    {
        $this->items = $items;
    }

    public function has($label)
    {
        return array_key_exists($label, $this->items);
    }

    public function get($label)
    {
        if (false === $this->has($label)) {
            throw new ItemNotFoundException($label);
        }

        return $this->items[$label];
    }

    final public function __get($label)
    {
        return $this->get($label);
    }

    final public function items(): array
    {
        return $this->items;
    }

    public function asArray(): array
    {
        throw new \RuntimeException('Method asArray not implemented');
    }
}

Remove final of 'has' method

Remove final of 'has' method


<tr<?php echo $event->getOutOfState() ?>>
  {{{ $event->getDate() }}}
  {{ $event->title }}
  @if (trim($event->location) == "Knights of Columbus")
  {{ $event->location }}
  @else
  {{ $event->location }}
  @endif

<tr<?php echo $event->getOutOfState() ?>>
  {{{ $event->getDate() }}}
  {{ $event->title }}
  @if (trim($event->location) == "Knights of Columbus")
  {{ $event->location }}
  @elseif (trim($event->address) != "")
  address }}}&z=12">{{ $event->location }}
  @else
  {{ $event->location }}
  @endif

Add support to link non Knights of Columbus locations to their address on google maps.


<?php

namespace Wnx\LaravelStats\Contracts;

use Wnx\LaravelStats\ReflectionClass;

interface Classifier
{
    /**
     * Component Name displayed in the results.
     *
     * @return string
     */
    public function name(): string;

    /**
     * Determine if the given ReflectionClass should be classified
     * as the component the Classifier Class represents.
     *
     * @param ReflectionClass $class
     * @return bool
     */
    public function satisfies(ReflectionClass $class);
}

<?php

namespace Wnx\LaravelStats\Contracts;

use Wnx\LaravelStats\ReflectionClass;

interface Classifier
{
    /**
     * Component Name displayed in the results.
     *
     * @return string
     */
    public function name(): string;

    /**
     * Determine if the given ReflectionClass should be classified
     * as the component the Classifier Class represents.
     *
     * @param \Wnx\LaravelStats\ReflectionClass $class
     * @return bool
     */
    public function satisfies(ReflectionClass $class): bool;
}

Set Return Typehint for satisfies

Set Return Typehint for satisfies


<?php

namespace Omise\Payment\Model\Api;

class Error extends Object
{
    /**
     * @var string
     */
    protected $code    = 'unexpected_error';
    protected $message = 'There is an unexpected error happened, please contact our support for further investigation.';

    public function __construct($error = array())
    {
        isset($error['code']) ? $this->setCode($error['code']);
        isset($error['message']) ? $this->setMessage($error['message']);
    }

    /**
     * @param string $code
     */
    protected function setCode($code)
    {
        $this->code = $code;
    }

    /**
     * @param string $message
     */
    protected function setMessage($message)
    {
        $this->message = $message;
    }

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

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

<?php

namespace Omise\Payment\Model\Api;

class Error extends Object
{
    /**
     * @var string
     */
    protected $code    = 'unexpected_error';
    protected $message = 'There is an unexpected error happened, please contact our support for further investigation.';

    public function __construct($error = array())
    {
        isset($error['code']) ? $this->setCode($error['code']) : '';
        isset($error['message']) ? $this->setMessage($error['message']) : '';
    }

    /**
     * @param string $code
     */
    protected function setCode($code)
    {
        $this->code = $code;
    }

    /**
     * @param string $message
     */
    protected function setMessage($message)
    {
        $this->message = $message;
    }

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

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

Fix syntax error for PHP legacy versions.


<?php namespace CSP\Test;

use CSP\Test\TestCase;
use CSP\Header\ContentSecurityPolicyHeader;
use CSP\Policy;
use CSP\Directive\DirectiveList;
use CSP\Directive\ScriptSrcDirective;
use CSP\Source\SourceList;
use CSP\Source\KeywordSource;

/**
 * @coversNothing
 */
class IntegrationTest extends TestCase
{
    public function testSimpleScriptDirective()
    {
        $header = new ContentSecurityPolicyHeader(new Policy(
            new DirectiveList(array(
                new ScriptSrcDirective(new SourceList(array(
                    new KeywordSource(KeywordSource::KEYWORD_SELF)
                )))
            ))
        ));

        $this->assertSame(
            "Content-Security-Policy: script-src 'self'",
            $header->render()
        );
    }
}

<?php namespace CSP\Test;

use CSP\Test\TestCase;
use CSP\Header\ContentSecurityPolicyHeader;
use CSP\Policy;
use CSP\Directive\DirectiveList;
use CSP\Directive\ScriptSrcDirective;
use CSP\Source\SourceList;
use CSP\Source\KeywordSource;

/**
 * @coversNothing
 */
class IntegrationTest extends TestCase
{
    public function testSimpleScriptDirective()
    {
        $header = new ContentSecurityPolicyHeader(
            new Policy(new DirectiveList(array(
                new ScriptSrcDirective(new SourceList(array(
                    new KeywordSource(KeywordSource::KEYWORD_SELF)
                )))
            )))
        );

        $this->assertSame(
            "Content-Security-Policy: script-src 'self'",
            $header->render()
        );
    }
}

Improve multiline indentation in tests

Improve multiline indentation in tests


<?php
/**
 * The template for displaying all pages.
 *
 * This is the template that displays all pages by default.
 * Please note that this is the WordPress construct of pages
 * and that other 'pages' on your WordPress site will use a
 * different template.
 *
 * @package _s
 * @since _s 1.0
 */

get_header(); ?>

				<?php while ( have_posts() ) : the_post(); ?>

					<?php get_template_part( 'content', 'page' ); ?>

          <?php
            // If comments are open or we have at least one comment, load up the comment template
            if ( comments_open() || '0' != get_comments_number() )
              comments_template( '', true );
          ?>

				<?php endwhile; // end of the loop. ?>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

Fix indentation on comments block

Fix indentation on comments block


<?php

return [
    'adminEmail' => 'admin@example.com',
];

<?php

return [
    'adminEmail' => 'admin@example.com',
    'pageSize' => 10,
];

Add configuration parameter for page size

This will determine how many links and comments to display per page.


<?php

namespace AshleyDawson\GlideBundle\DependencyInjection;

use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;

/**
 * Class Configuration
 *
 * @package AshleyDawson\GlideBundle\DependencyInjection
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();

        $rootNode = $treeBuilder->root('ashley_dawson_glide');

        $rootNode
            ->children()
                ->integerNode('max_image_size')->defaultValue(4000000)->end()
                ->scalarNode('image_manager_driver')->defaultValue('gd')->end()
            ->end()
        ;

        return $treeBuilder;
    }
}

<?php

namespace AshleyDawson\GlideBundle\DependencyInjection;

use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;

/**
 * Class Configuration
 *
 * @package AshleyDawson\GlideBundle\DependencyInjection
 */
class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('ashley_dawson_glide');

        $rootNode = $treeBuilder->getRootNode();

        $rootNode
            ->children()
                ->integerNode('max_image_size')->defaultValue(4000000)->end()
                ->scalarNode('image_manager_driver')->defaultValue('gd')->end()
            ->end()
        ;

        return $treeBuilder;
    }
}

Update TreeBuilder instantiation - fixing 4.3 deprecation


<?php
/**
     *
     *
     * @author Sam Schmidt
     * @date 2015-04-22
     * @company Linus Shops
     */

namespace LinusShops\Prophet;

use LinusShops\Prophet\Exceptions\InvalidConfigException;
use Symfony\Component\Yaml\Parser;

class Config
{
    private $modules;

    public function __construct($parsedConfigFile, $prefix = '')
    {
        if (!is_array($parsedConfigFile)) {
            throw new InvalidConfigException('Invalid config: parsed config must be an array.');
        }

        if (isset($parsedConfigFile['modules'])) {
            $this->loadModules($parsedConfigFile['modules']);
        }
    }

    /**
     * @param string $path
     * @return Config
     * @throws InvalidConfigException
     */
    public static function getConfigFromFile($path = '.')
    {
        $path .= '/prophet.yml';

        if (!is_file($path)) {
            throw new InvalidConfigException('Invalid config path given.');
        }
        $yaml = new Parser();

        return new Config($yaml->parse(file_get_contents($path)));
    }

    private function loadModules($modules)
    {
        foreach ($modules as $definition) {
            $module = new Module(
                $definition['name'],
                $definition['path']
            );

            $this->modules[$module->getName()] = $module;
        }
    }

    public function getModules()
    {
        return $this->modules;
    }

    public function hasModules()
    {
        return count($this->modules) > 0;
    }
}

<?php
/**
     *
     *
     * @author Sam Schmidt
     * @date 2015-04-22
     * @company Linus Shops
     */

namespace LinusShops\Prophet;

use LinusShops\Prophet\Exceptions\InvalidConfigException;
use Symfony\Component\Yaml\Parser;

class Config
{
    private $modules;

    public function __construct($parsedConfigFile, $prefix = '')
    {
        if (!is_array($parsedConfigFile)) {
            throw new InvalidConfigException('Invalid config: parsed config must be an array.');
        }

        if (isset($parsedConfigFile['modules'])) {
            $this->loadModules($parsedConfigFile['modules']);
        }
    }

    /**
     * @param string $path
     * @return Config
     * @throws InvalidConfigException
     */
    public static function getConfigFromFile($path = '.')
    {
        $path .= '/prophet.yml';

        if (!is_file($path)) {
            throw new InvalidConfigException("prophet.yml not found in path {$path}");
        }
        $yaml = new Parser();

        return new Config($yaml->parse(file_get_contents($path)));
    }

    private function loadModules($modules)
    {
        foreach ($modules as $definition) {
            $module = new Module(
                $definition['name'],
                $definition['path']
            );

            $this->modules[$module->getName()] = $module;
        }
    }

    public function getModules()
    {
        return $this->modules;
    }

    public function hasModules()
    {
        return count($this->modules) > 0;
    }
}

Improve error message when prophet.yml not found.


<?php

namespace OrgManager\ApiClient;

use GuzzleHttp\Client;

class OrgManager
{
    /** @var \GuzzleHttp\Client */
    protected $client;

    /** @var string */
    protected $baseUrl;

    /**
     * @param \GuzzleHttp\Client $client
     * @param string             $apiToken
     * @param string             $rootUrl
     */
    public function __construct(Client $client, $apiToken, $rootUrl = 'https://orgmanager.miguelpiedrafita.com')
    {
        $this->client = $client;

        $this->apiToken = $apiToken;

        $this->baseUrl = $rootUrl.'/api';
    }

    /**
     *
     * @return array
     */
    public function getRoot()
    {
        return $this->get('');
    }

    /**
     * @param string $resource
     * @param array  $query
     *
     * @return array
     */
    public function get($resource, array $query = [])
    {
        $query['api_token'] = $this->apiToken;

        $results = $this->client
            ->get("{$this->baseUrl}{$resource}", compact('query'))
            ->getBody()
            ->getContents();

        return json_decode($results, true);
    }
}

<?php

namespace OrgManager\ApiClient;

use GuzzleHttp\Client;

class OrgManager
{
    /** @var \GuzzleHttp\Client */
    protected $client;

    /** @var string */
    protected $baseUrl;

    /**
     * @param \GuzzleHttp\Client $client
     * @param string             $apiToken
     * @param string             $rootUrl
     */
    public function __construct(Client $client, $apiToken, $rootUrl = 'https://orgmanager.miguelpiedrafita.com')
    {
        $this->client = $client;

        $this->apiToken = $apiToken;

        $this->baseUrl = $rootUrl.'/api';
    }

    /**
     *
     * @return array
     */
    public function getRoot()
    {
        return $this->get('');
    }

    /**
     *
     * @return array
     */
    public function getStats()
    {
        return $this->get('/stats');
    }

    /**
     * @param string $resource
     * @param array  $query
     *
     * @return array
     */
    public function get($resource, array $query = [])
    {
        $query['api_token'] = $this->apiToken;

        $results = $this->client
            ->get("{$this->baseUrl}{$resource}", compact('query'))
            ->getBody()
            ->getContents();

        return json_decode($results, true);
    }
}

Add function to get stats

Add function to get stats


<?php

/*
 *  @author Serkin Akexander <serkin.alexander@gmail.com>
 */

namespace Volan\Validator;

class StringValidator extends AbstractValidator
{
    /**
     * Validate wether given data is string.
     *
     * @param mixed $nodeData
     *
     * @return bool
     */
    public function isValid($nodeData)
    {
        return (!empty($nodeData) && is_string($nodeData));
    }
}

<?php

/*
 *  @author Serkin Akexander <serkin.alexander@gmail.com>
 */

namespace Volan\Validator;

class StringValidator extends AbstractValidator
{
    /**
     * Validate wether given data is string.
     *
     * @param mixed $nodeData
     *
     * @return bool
     */
    public function isValid($nodeData)
    {
        return (is_string($nodeData) && $nodeData != "");
    }
}

Allow for '0' when type is required_string


<?php

namespace Profideo\FormulaInterpreterBundle\Excel\ExpressionLanguage\ExpressionFunction;

/**
 * Represents the "ROUND" function that can be used in an expression.
 */
class RoundExpressionFunction extends ExpressionFunction
{
    /**
     * @return string
     */
    protected function getCompilerFunction()
    {
        return sprintf('%s(%s, %s)', $this->getName(), func_get_arg(0), func_get_arg(1));
    }

    /**
     * @return float
     */
    protected function getEvaluatorFunction()
    {
        return round(func_get_arg(1), func_get_arg(2), PHP_ROUND_HALF_UP);
    }

    /**
     * {@inheritdoc}
     */
    protected function getMinArguments()
    {
        return 2;
    }

    /**
     * {@inheritdoc}
     */
    protected function getMaxArguments()
    {
        return 2;
    }
}

<?php

namespace Profideo\FormulaInterpreterBundle\Excel\ExpressionLanguage\ExpressionFunction;

use Profideo\FormulaInterpreterBundle\Excel\ExpressionLanguage\ExpressionError;

/**
 * Represents the "ROUND" function that can be used in an expression.
 */
class RoundExpressionFunction extends ExpressionFunction
{
    /**
     * @return string
     */
    protected function getCompilerFunction()
    {
        return sprintf('%s(%s, %s)', $this->getName(), func_get_arg(0), func_get_arg(1));
    }

    /**
     * @return float
     */
    protected function getEvaluatorFunction()
    {
        $args = func_get_args();

        if (! is_numeric($args[1])) {
            throw new ExpressionError(
                sprintf('The function %s expects numeric as parameter 1 but "%s" given', $this->getName(), gettype($args[1]))
            );
        }

        if (! is_int($args[2])) {
            throw new ExpressionError(
                sprintf('The function %s expects integer as parameter 2 but "%s" given', $this->getName(), gettype($args[2]))
            );
        }

        return round($args[1], $args[2], PHP_ROUND_HALF_UP);
    }

    /**
     * {@inheritdoc}
     */
    protected function getMinArguments()
    {
        return 2;
    }

    /**
     * {@inheritdoc}
     */
    protected function getMaxArguments()
    {
        return 2;
    }
}

Add checks for ROUND function

Add checks for ROUND function


<?php
use League\CommonMark\CommonMarkConverter;

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

function getVersion() {
    $lock = json_decode(file_get_contents(__DIR__.'/../composer.lock'), true);
    foreach ($lock['packages'] as $package) {
        if ($package['name'] === 'league/commonmark') {
            return $package['version'];
        }
    }

    return 'latest';
}

if (!isset($_GET['text'])) {
    $markdown = '';
} else {
    $markdown = $_GET['text'];
    if (mb_strlen($markdown) > 1000) {
        http_response_code(413); // Request Entity Too Large
        $markdown = "Input must be less than 1,000 characters";
    }
}

$converter = new CommonMarkConverter();
$html = $converter->convertToHtml($markdown);

header('Content-Type: application/json');
echo json_encode([
    'name' => 'league/commonmark',
    'version' => getVersion(),
    'html' => $html,
]);

<?php
use League\CommonMark\CommonMarkConverter;

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

function getVersion() {
    if (defined('League\CommonMark\CommonMarkConverter::VERSION')) {
        $version = CommonMarkConverter::VERSION;
        if (preg_match('/^[\d\.]+/$', $version) === 1) {
            return $version;
        }
    }

    $lock = json_decode(file_get_contents(__DIR__.'/../composer.lock'), true);
    foreach ($lock['packages'] as $package) {
        if ($package['name'] === 'league/commonmark') {
            return $package['version'];
        }
    }

    if (isset($version)) {
        return $version;
    }

    return 'latest';
}

if (!isset($_GET['text'])) {
    $markdown = '';
} else {
    $markdown = $_GET['text'];
    if (mb_strlen($markdown) > 1000) {
        http_response_code(413); // Request Entity Too Large
        $markdown = "Input must be less than 1,000 characters";
    }
}

$converter = new CommonMarkConverter();
$html = $converter->convertToHtml($markdown);

header('Content-Type: application/json');
echo json_encode([
    'name' => 'league/commonmark',
    'version' => getVersion(),
    'html' => $html,
]);

Use the VERSION constant if available

Use the VERSION constant if available


<?php

use Illuminate\Database\Seeder;

class TypeSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('types')->insert([

          'contentType' => 'TEST',
          'expectedFields' =>  '
            "TestField1" => "true",
            "TestField2" => "true",
          ',
        ]);

    }
}

<?php

use Illuminate\Database\Seeder;

class TypeSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     *  For expected fields, hstore specify as follows
     *    "Field Name" => "length of field (Short, medium, long, box),
     *                    required field (true,false), lock display on form at (top, bottom, none)"
     *
     * @return void
     */
    public function run()
    {
        DB::table('types')->insert([

          'contentType' => 'Story',
          'expectedFields' =>  '
            "Source" => "short,true,top",
            "Title" => "short,true,none",
            "Author" => "short,true,none",
            "Summary" => "box,false,bottom",
          ',
        ]);

        DB::table('types')->insert([

          'contentType' => 'Art',
          'expectedFields' =>  '
            "Source" => "short,true,top",
            "Title" => "short,false,none",
            "Artist" => "short,true,none",
            "Description" => "box,false,bottom",
          ',
        ]);

        DB::table('types')->insert([

          'contentType' => 'Blog',
          'expectedFields' =>  '
            "Blog Name" => "short,true,none",
            "Owner" => "short,true,none",
            "Description" => "box,false,bottom",
          ',
        ]);

        DB::table('types')->insert([

          'contentType' => 'Website',
          'expectedFields' =>  '
            "Site Name" => "short,true,none",
            "Owner" => "short,false,none",
            "Description" => "box,false,bottom",
          ',
        ]);

        DB::table('types')->insert([

          'contentType' => 'Video',
          'expectedFields' =>  '
            "Source" => "short,true,top",
            "Title" => "short,true,none",
            "By" => "short,true,none",
            "Description" => "box,false,bottom",
          ',
        ]);

    }
}

Add proper types seeds and reseed

Add proper types seeds and reseed


<?php
/**
 * Created by JetBrains PhpStorm.
 * User: shanthi
 * Date: 07/09/2011
 * Time: 11:45
 * To change this template use File | Settings | File Templates.
 */

<?php
class ContactFormTest extends CDbTestCase
{
	public $model;

	public function setUp()
	{
		parent::setUp();
		$this->model = new ContactForm;
	}

	public function testAttributeLabels()
	{
		$expected = array(
			'verifyCode'=>'Verification Code',
		);

		$this->assertEquals($expected, $this->model->attributeLabels(), 'Attribute labels should match.');
	}
}

Add tests for ContactForm model (OE-37)

Add tests for ContactForm model (OE-37)


<?php

namespace WpListings;

class App
{
    public static $uploadDir;

    public function __construct()
    {
        self::$uploadDir = $this->getUploadDir();
        add_filter('acf/settings/load_json', array($this, 'jsonLoadPath'));

        new \WpListings\Listings();
        new \WpListings\FrontendForm();
        new \WpListings\Options();
    }

    /**
     * Set ACF json load paths
     * @param  array $paths  Original paths
     * @return array         Modified paths
     */
    public function jsonLoadPath($paths)
    {
        $paths[] = WPLISTINGS_PATH . 'source/acf-exports';
        $paths[] = $this->getUploadDir();

        return $paths;
    }

    /**
     * Get upload directory path
     * @return string
     */
    public function getUploadDir()
    {
        if (isset(self::$uploadDir)) {
            return self::$uploadDir;
        }

        $uploadDir = wp_upload_dir();
        $uploadDir = $uploadDir['basedir'] . '/wp-listings-fields';

        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0777);
        }

        return $uploadDir;
    }
}

<?php

namespace WpListings;

class App
{
    public static $uploadDir;

    public function __construct()
    {
        add_action('plugins_loaded', array($this, 'init'));
    }

    public function init()
    {
        if (!function_exists('get_field') && !function_exists('acf_add_options_page')) {
            add_action('admin_notices', function () {
                echo '

', __('WP Listings: Please activate Advanced Custom Fields plugin to be able to use WP Listings.', 'wp-listings'), '

';
            });

            return;
        }

        self::$uploadDir = $this->getUploadDir();
        add_filter('acf/settings/load_json', array($this, 'jsonLoadPath'));

        new \WpListings\Listings();
        new \WpListings\FrontendForm();
        new \WpListings\Options();
    }

    /**
     * Set ACF json load paths
     * @param  array $paths  Original paths
     * @return array         Modified paths
     */
    public function jsonLoadPath($paths)
    {
        $paths[] = WPLISTINGS_PATH . 'source/acf-exports';
        $paths[] = $this->getUploadDir();

        return $paths;
    }

    /**
     * Get upload directory path
     * @return string
     */
    public function getUploadDir()
    {
        if (isset(self::$uploadDir)) {
            return self::$uploadDir;
        }

        $uploadDir = wp_upload_dir();
        $uploadDir = $uploadDir['basedir'] . '/wp-listings-fields';

        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0777);
        }

        return $uploadDir;
    }
}

Check acf availability before init

Check acf availability before init


<div class="alert <?php echo isset($error_type) ? $error_type : "alert-danger"; ?> alert-wide">
	<?php echo $error_message; ?>

Allow alternative colors in alert template

Signed-off-by: Florian Pritz <753f544d2d01592750fb4bd29251b78abcfc8ecd@xinu.at>


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Milestone extends Model
{

  public $timestamps = false;

  protected $fillable = [
      'name','description','start_at','due_at','end_at',
  ];

  public function tickets()
  {
      return $this->hasMany('App\Ticket');
  }
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Milestone extends Model
{

  public $timestamps = false;

  protected $fillable = [
      'name','description','scrummaster_user_id','owner_user_id','start_at','due_at','end_at',
  ];

  public function tickets()
  {
      return $this->hasMany('App\Ticket');
  }

  public function owner()
  {
      return $this->hasOne('App\User','id','owner_user_id');
  }

  public function scrummaster()
  {
      return $this->hasOne('App\User','id','scrummaster_user_id');
  }
}

Add sprint owner and scrum master

Add sprint owner and scrum master


<?php declare(strict_types=1);

namespace Wnx\LaravelStats\ShareableMetrics;

use Illuminate\Support\Collection;

class MetricsCollection extends Collection
{
    public function toAsciiTableFormat(): array
    {
        $projectMetrics = $this->items['project_metrics']
            ->map(function ($metric) {
                if (is_array($metric)) {
                    return json_encode($metric, JSON_PRETTY_PRINT);
                }

                if ($metric === true) {
                    return 'true';
                }

                if ($metric === false) {
                    return 'false';
                }

                return $metric;
            });

        return $projectMetrics
            ->forget('packages')
            ->keys()
            ->zip($projectMetrics)
            ->toArray();
    }

    public function toHttpPayload(string $projectName): array
    {
        $projectMetrics = $this->get('project_metrics');
        $componentMetrics = $this->get('component_metrics');

        return [
            'project' => $projectName,
            'metrics' => $projectMetrics
                ->merge($componentMetrics)
                ->sortKeys()
                ->toArray()
        ];
    }
}

<?php declare(strict_types=1);

namespace Wnx\LaravelStats\ShareableMetrics;

use Illuminate\Support\Collection;

class MetricsCollection extends Collection
{
    public function toAsciiTableFormat(): array
    {
        $projectMetrics = $this->items['project_metrics']
            ->map(function ($metric) {
                if (is_array($metric)) {
                    return json_encode($metric, JSON_PRETTY_PRINT);
                }

                if ($metric === true) {
                    return 'true';
                }

                if ($metric === false) {
                    return 'false';
                }

                return $metric;
            })
            ->sort();

        return $projectMetrics
            ->forget('packages')
            ->keys()
            ->zip($projectMetrics)
            ->toArray();
    }

    public function toHttpPayload(string $projectName): array
    {
        $projectMetrics = $this->get('project_metrics');
        $componentMetrics = $this->get('component_metrics');

        return [
            'project' => $projectName,
            'metrics' => $projectMetrics
                ->merge($componentMetrics)
                ->sortKeys()
                ->toArray()
        ];
    }
}

Sort Metrics displayed in ASCII Table

Sort Metrics displayed in ASCII Table


<?php

require_once __DIR__.'/../vendor/functional-php/src/Functional/_import.php';

require_once __DIR__.'/Slot.php';
require_once __DIR__.'/SlotGroup.php';
require_once __DIR__.'/Size.php';
require_once __DIR__.'/Source.php';
require_once __DIR__.'/SrcsetGeneratorInterface.php';
require_once __DIR__.'/srcset_generators/Drupal.php';

<?php

require_once __DIR__.'/../../vendor/functional-php/src/Functional/_import.php';

require_once __DIR__.'/Slot.php';
require_once __DIR__.'/SlotGroup.php';
require_once __DIR__.'/Size.php';
require_once __DIR__.'/Source.php';
require_once __DIR__.'/SrcsetGeneratorInterface.php';
require_once __DIR__.'/srcset_generators/Drupal.php';

Fix broken require for functional-php

Fix broken require for functional-php


<?php

/*
 * This file is part of the Elcodi package.
 *
 * Copyright (c) 2014-2015 Elcodi.com
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * Feel free to edit as you please, and have fun.
 *
 * @author Marc Morera <yuhu@mmoreram.com>
 * @author Aldo Chiecchia <zimage@tiscali.it>
 * @author Elcodi Team <tech@elcodi.com>
 */

namespace Elcodi\Plugin\GoogleAnalyticsBundle;

use Symfony\Component\Console\Application;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
use Symfony\Component\HttpKernel\Bundle\Bundle;

use Elcodi\Component\Plugin\Interfaces\PluginInterface;
use Elcodi\Plugin\GoogleAnalyticsBundle\DependencyInjection\ElcodiGoogleAnalyticsExtension;

/**
 * Class ElcodiGoogleAnalyticsBundle
 */
class ElcodiGoogleAnalyticsBundle extends Bundle implements PluginInterface
{
    /**
     * Returns the bundle's container extension.
     *
     * @return ExtensionInterface The container extension
     */
    public function getContainerExtension()
    {
        return new ElcodiGoogleAnalyticsExtension();
    }

    /**
     * Register Commands.
     *
     * Disabled as commands are registered as services.
     *
     * @param Application $application An Application instance
     */
    public function registerCommands(Application $application)
    {
        return null;
    }
}

<?php

/*
 * This file is part of the Elcodi package.
 *
 * Copyright (c) 2014-2015 Elcodi.com
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * Feel free to edit as you please, and have fun.
 *
 * @author Marc Morera <yuhu@mmoreram.com>
 * @author Aldo Chiecchia <zimage@tiscali.it>
 * @author Elcodi Team <tech@elcodi.com>
 */

namespace Elcodi\Plugin\GoogleAnalyticsBundle;

use Symfony\Component\Console\Application;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
use Symfony\Component\HttpKernel\Bundle\Bundle;

use Elcodi\Component\Plugin\Interfaces\PluginInterface;
use Elcodi\Plugin\GoogleAnalyticsBundle\DependencyInjection\ElcodiGoogleAnalyticsExtension;

/**
 * Class ElcodiGoogleAnalyticsBundle
 */
class ElcodiGoogleAnalyticsBundle extends Bundle implements PluginInterface
{
    /**
     * Returns the bundle's container extension.
     *
     * @return ExtensionInterface The container extension
     */
    public function getContainerExtension()
    {
        return new ElcodiGoogleAnalyticsExtension();
    }

    /**
     * Register Commands.
     *
     * Disabled as commands are registered as services.
     *
     * @param Application $application An Application instance
     *
     * @return null
     */
    public function registerCommands(Application $application)
    {
        return null;
    }
}

Store + Shipping + Menus

Store + Shipping + Menus

* Using new Store feature from Elcodi
* Added Store management in Admin
* Changed all definitions that was depending on such implementation
* Removed under construction logic and tests

* Removed menu fixtures
* Defined them as dynamic content. Some of them are generated dinamically, and
  some of them statically.
* Added neede menu builders in every Admin bundle
* Changed the way menu is loaded in Admin

* Removed dependency with Configuration and Configuration annotation, in order to use
  new implementation.
* Removed configuration elements
* Removed all `elcodi_config` twig extension usage

* Moved custom shipping logic from elcodi/elcodi to elcodi-plugins/*
* Added full repo inside Plugin folder
* Using new Shipping engine

* Updated some code in order to be compatible with Sf2.7 deprecations

Ready for Elcodi Beta! Auu! Auu!


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

namespace Darvin\Utils\HttpFoundation;

use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * AJAX response
 */
class AjaxResponse extends JsonResponse
{
    /**
     * @param string $html       HTML
     * @param bool   $success    Is success
     * @param string $message    Message
     * @param bool   $reloadPage Whether to reload page
     * @param int    $status     Response status code
     * @param array  $headers    Response headers
     */
    public function __construct($html = '', $success = true, $message = null, $reloadPage = false, $status = 200, $headers = array())
    {
        parent::__construct(array(
            'html'       => $html,
            'message'    => $message,
            'reloadPage' => $reloadPage,
            'success'    => $success,
        ), $status, $headers);
    }
}

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

namespace Darvin\Utils\HttpFoundation;

use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * AJAX response
 */
class AjaxResponse extends JsonResponse
{
    /**
     * @param string $html       HTML
     * @param bool   $success    Is success
     * @param string $message    Message
     * @param bool   $reloadPage Whether to reload page
     * @param array  $data       Additional data
     * @param int    $status     Response status code
     * @param array  $headers    Response headers
     */
    public function __construct(
        $html = '',
        $success = true,
        $message = null,
        $reloadPage = false,
        array $data = array(),
        $status = 200,
        array $headers = array()
    ) {
        parent::__construct(array_merge($data, array(
            'html'       => $html,
            'message'    => $message,
            'reloadPage' => $reloadPage,
            'success'    => $success,
        ), $status, $headers));
    }
}

Add "data" argument to AJAX response class constructor.


<?php

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

class AddSortColumnToStoriesTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('stories', function(Blueprint $table) {
            $table->integer('sort')->unsigned()->default(1);
            $table->unique(['sort', 'issue_id']);
        });
    }

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

}

<?php

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

class AddSortColumnToStoriesTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('stories', function(Blueprint $table) {
            $table->smallInteger('sort')->unsigned()->default(1);
            $table->unique(['sort', 'issue_id']);
        });
    }

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

}

Use smallint for sort column on stories table


<?php

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;
}

<?php

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
	use CreatesApplication;

	protected function disableExceptionHandling()
	{
		$this->app->instance(ExceptionHandler::class, new class extends Handler {
			public function __construct()
			{
			}
			public function report(Exception $e)
			{
			}
			public function render($request, Exception $e)
			{
				throw $e;
			}
		});
	}
}

Add helper function for testing

Add helper function for testing

This function stop laravel from translating php errors into http errors


<?php

use Illuminate\Foundation\Testing\DatabaseTransactions;

class SendBusinessReportTest extends TestCase
{
    use DatabaseTransactions;

    /**
     * @test
     */
    public function it_sends_business_report()
    {
        $exitCode = Artisan::call('business:report');

        $resultAsText = Artisan::output();

        $this->assertEquals(0, $exitCode);
        $this->assertEquals($resultAsText, "Scanning all businesses...\n");
    }
}

<?php

use Illuminate\Foundation\Testing\DatabaseTransactions;
use Timegridio\Concierge\Models\Appointment;

class SendBusinessReportTest extends TestCase
{
    use DatabaseTransactions;
    use CreateBusiness, CreateUser, CreateContact, CreateAppointment, CreateService, CreateVacancy;

    /**
     * @test
     */
    public function it_sends_business_report()
    {
        $this->arrangeFixture();

        $exitCode = Artisan::call('business:report');

        $resultAsText = Artisan::output();

        $this->assertEquals(0, $exitCode);
        $this->assertContains('Scanning all businesses...', $resultAsText);
    }

    /**
     * Arrange Fixture.
     *
     * @return void
     */
    protected function arrangeFixture()
    {
        $this->owner = $this->createUser();

        $this->issuer = $this->createUser();

        $this->business = $this->createBusiness();
        $this->business->owners()->save($this->owner);

        $this->contact = $this->createContact();

        $this->contact->user()->associate($this->issuer);

        $this->service = $this->makeService();
        $this->business->services()->save($this->service);

        $this->vacancy = $this->makeVacancy();
        $this->vacancy->service()->associate($this->service);
        $this->business->vacancies()->save($this->vacancy);

        $appointment = $this->makeAppointment($this->business, $this->issuer, $this->contact, [
            'status' => Appointment::STATUS_CONFIRMED,
            ]);
    }
}

Fix test case to fit an scenario

Fix test case to fit an scenario


<?php

namespace Laravie\Authen\Tests;

use Orchestra\Testbench\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    /**
     * Setup the test environment.
     */
    protected function setUp(): void
    {
        parent::setUp();

        $this->withFactories(__DIR__.'/factories');
        $this->loadMigrationsFrom([
            '--database' => 'testing',
            '--realpath' => realpath(__DIR__.'/migrations'),
        ]);
    }

    /**
     * Get package providers.
     *
     * @param  \Illuminate\Foundation\Application  $app
     *
     * @return array
     */
    protected function getPackageProviders($app)
    {
        return [
            \Laravie\Authen\AuthenServiceProvider::class,
            \Laravie\Authen\Tests\Stubs\AuthServiceProvider::class,
        ];
    }

    /**
     * Define environment setup.
     *
     * @param  \Illuminate\Foundation\Application   $app
     *
     * @return void
     */
    protected function getEnvironmentSetUp($app)
    {
        $config = $app->make('config');

        $config->set([
            'auth.providers.users' => [
                'driver' => 'authen',
                'model' => \Laravie\Authen\Tests\Stubs\User::class,
            ],
        ]);
    }
}

<?php

namespace Laravie\Authen\Tests;

use Orchestra\Testbench\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    /**
     * Setup the test environment.
     */
    protected function setUp(): void
    {
        parent::setUp();

        $this->withFactories(__DIR__.'/factories');
        $this->loadMigrationsFrom([
            '--database' => 'testing',
            '--path' => realpath(__DIR__.'/migrations'),
        ]);
    }

    /**
     * Get package providers.
     *
     * @param  \Illuminate\Foundation\Application  $app
     *
     * @return array
     */
    protected function getPackageProviders($app)
    {
        return [
            \Laravie\Authen\AuthenServiceProvider::class,
            \Laravie\Authen\Tests\Stubs\AuthServiceProvider::class,
        ];
    }

    /**
     * Define environment setup.
     *
     * @param  \Illuminate\Foundation\Application   $app
     *
     * @return void
     */
    protected function getEnvironmentSetUp($app)
    {
        $config = $app->make('config');

        $config->set([
            'auth.providers.users' => [
                'driver' => 'authen',
                'model' => \Laravie\Authen\Tests\Stubs\User::class,
            ],
        ]);
    }
}

Use --path instead of --realpath

Use --path instead of --realpath

Signed-off-by: Mior Muhammad Zaki <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>


<?php

namespace Slakbal\Gotowebinar;

use Slakbal\Gotowebinar\Traits\GotoClient;

class DirectLogin
{

    use GotoClient;

    protected $path = 'oauth/access_token';

    public function authenticate()
    {
        return $this->getAuthObject($this->path, $this->getParameters());
    }

    private function getParameters()
    {
        return [
            'grant_type' => "password",
            'user_id'    => config('goto.direct.username'),
            'password'   => config('goto.direct.password'),
            'client_id'  => config('goto.direct.client_id'),
        ];
    }

}

<?php

namespace Slakbal\Gotowebinar;

use Slakbal\Gotowebinar\Traits\GotoClient;

class DirectLogin
{

    use GotoClient;

    protected $path = 'oauth/v2/token';

    public function authenticate()
    {
        return $this->getAuthObject($this->path, $this->getParameters());
    }

    private function getParameters()
    {
        return [
            'grant_type' => "password",
            'username'    => config('goto.direct.username'),
            'password'   => config('goto.direct.password')
        ];
    }
}

Remove client_id as it is not required in the body of the request


<?php

namespace Airbrake\Errors;

/**
 * Error wrapper that mimics Exception API. For internal usage.
 */
class Base
{
    private $message;
    private $file;
    private $line;
    private $trace;

    public function __construct($message, $trace = [])
    {
        $this->message = $message;
        $frame = array_shift($trace);
        if ($frame != null) {
            $this->file = $frame['file'];
            $this->line = $frame['line'];
        }
        $this->trace = $trace;
    }

    public function getMessage()
    {
        return $this->message;
    }

    public function getFile()
    {
        return $this->file;
    }

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

    public function getTrace()
    {
        return $this->trace;
    }
}

<?php

namespace Airbrake\Errors;

/**
 * Error wrapper that mimics Exception API. For internal usage.
 */
class Base
{
    private $message;
    private $file;
    private $line;
    private $trace;

    public function __construct($message, $trace = [])
    {
        $this->message = $message;
        $frame = array_shift($trace);
        if ($frame != null) {
            if (isset($frame['file'])) {
                $this->file = $frame['file'];
            }
            if (isset($frame['line'])) {
                $this->line = $frame['line'];
            }
        }
        $this->trace = $trace;
    }

    public function getMessage()
    {
        return $this->message;
    }

    public function getFile()
    {
        return $this->file;
    }

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

    public function getTrace()
    {
        return $this->trace;
    }
}

Check for file and line before assignment

If the file, line, or both are missing, this breaks completely.


<?php

class ThirdParty {

	public static function init() {
		spl_autoload_register(array(self, '::autoload'), true, true);
	}

	public static function autoload($class) {

		$class_array = explode('\\', $class);
		if (count($class_array)>1) {
			if ($class_array[0] == 'ThirdParty') {
				$file_load = Config::get('path.third_party').'/'.$class_array[1].'/'.$class_array[2].'.php';
				if (file_exists($file_load)) {
					$namespace = "<?php\nnamespace ThirdParty\\$class_array[1];\n?>\n";
					$thirdpartyfile = fopen($file_load, "r");
					$thirdpartyclass = fread($thirdpartyfile,filesize($file_load));
					fclose($thirdpartyfile);
					eval("?>$namespace.$thirdpartyclass");

					//include_once $file_load;
				}
			}
		}
	}
}

<?php

function ThirdPartyAutoload($class) {
	$class_array = explode('\\', $class);

	//if (count($class_array)>1) {
		//if ($class_array[0] == 'ThirdParty') {

			if (isset($class_array[1]))
				$file_load = \Kecik\Config::get('path.third_party').'/'.$class_array[0].'/'.$class_array[1].'.php';
			else
				$file_load = \Kecik\Config::get('path.third_party').'/'.$class_array[0].'/'.$class_array[0].'.php';

			if (file_exists($file_load)) {
				include_once $file_load;
			} else {
				$file_load = \Kecik\Config::get('path.third_party').'/'.$class_array[0].'.php';
				if (file_exists($file_load))
					include_once $file_load;
			}
		//}
	//}
}

spl_autoload_register('ThirdPartyAutoload');

Change Autoload Third Party to Global Class


<?php

use Cake\Cache\Cache;
use Cake\Core\Configure;
use Croogo\Core\Croogo;

if (Configure::read('Site.acl_plugin') == 'Croogo/Acl') {

	// activate AclFilter component only until after a succesful install
	if (file_exists(APP . 'config' . DS . 'settings.json')) {
		Croogo::hookComponent('*', 'Croogo/Acl.AclFilter');
		Croogo::hookComponent('*', array(
			'CroogoAccess' => array(
				'className' => 'Croogo/Acl.AclAccess',
			),
		));
	}

//	Croogo::hookBehavior('Croogo/Users.Users', 'Croogo/Acl.UserAro');
//	Croogo::hookBehavior('Croogo/Users.Roles', 'Croogo/Acl.RoleAro');

	Cache::config('permissions', array(
		'duration' => '+1 hour',
		'path' => CACHE . 'queries' . DS,
		'className' => Configure::read('Croogo.Cache.defaultEngine'),
		'prefix' => Configure::read('Croogo.Cache.defaultPrefix'),
		'groups' => array('acl')
	));
}

<?php

use Cake\Cache\Cache;
use Cake\Core\Configure;
use Croogo\Core\Croogo;

if (Configure::read('Site.acl_plugin') == 'Croogo/Acl') {

	// activate AclFilter component only until after a succesfull install
	if (Configure::read('Site.status')) {
		Croogo::hookComponent('*', 'Croogo/Acl.Filter');
		Croogo::hookComponent('*', array(
			'CroogoAccess' => array(
				'className' => 'Croogo/Acl.Access',
			),
		));
	}

//	Croogo::hookBehavior('Croogo/Users.Users', 'Croogo/Acl.UserAro');
//	Croogo::hookBehavior('Croogo/Users.Roles', 'Croogo/Acl.RoleAro');

	Cache::config('permissions', array(
		'duration' => '+1 hour',
		'path' => CACHE . 'queries' . DS,
		'className' => Configure::read('Croogo.Cache.defaultEngine'),
		'prefix' => Configure::read('Croogo.Cache.defaultPrefix'),
		'groups' => array('acl')
	));
}

Use Site.installed as check for a installed site


<?php
declare(strict_types = 1);

namespace Apha\Examples;

/* @var $loader \Composer\Autoload\ClassLoader */
$loader = require_once __DIR__ . '/../../vendor/autoload.php';
$loader->addPsr4("Apha\\Examples\\", __DIR__ . "/");

\Doctrine\Common\Annotations\AnnotationRegistry::registerAutoloadNamespace(
    'JMS\Serializer\Annotation', __DIR__ . '/../../vendor/jms/serializer/src'
);

abstract class Runner
{
    /**
     * @return int
     */
    public static function main(): int
    {
        (new static())->run();
        return 0;
    }

    /**
     * @return void
     */
    abstract public function run();
}

<?php
declare(strict_types = 1);

namespace Apha\Examples;

/* @var $loader \Composer\Autoload\ClassLoader */
use Doctrine\Common\Annotations\AnnotationRegistry;

$loader = require_once __DIR__ . '/../../vendor/autoload.php';
$loader->addPsr4("Apha\\Examples\\", __DIR__ . "/");

AnnotationRegistry::registerLoader(function (string $className) use ($loader) {
    return $loader->loadClass($className);
});

abstract class Runner
{
    /**
     * @return int
     */
    public static function main(): int
    {
        (new static())->run();
        return 0;
    }

    /**
     * @return void
     */
    abstract public function run();
}

Use regular autoloader for loading annotations.


<?php

function wp_bootstrap_hooks() {

  require_once "bootstrap-comments.php";
  require_once "bootstrap-content.php";
  require_once "bootstrap-gallery.php";
  require_once "bootstrap-menu.php";
  require_once "bootstrap-pagination.php";
  require_once "bootstrap-searchform.php";
  require_once "bootstrap-widgets.php";

}

<?php

/**
 Plugin Name: Bootstrap Hooks
 Plugin URI: http://github.com/benignware/wp-bootstrap-hooks
 Description: A collection of action and filters for bootstrap based themes
 Version: 0.0.1
 Author: Rafael Nowrotek, Benignware
 Author URI: http://benignware.com
 License: MIT
*/

function wp_bootstrap_hooks() {
  $args = func_get_args();
  if (!count($args)) {
    $args = array('comments', 'content', 'forms', 'gallery', 'menu', 'pagination', 'widgets');
  }
  foreach ($args as $arg) {
    require_once "bootstrap-$arg.php";
  }
}

// If file resides in template directory, require all immediately
if (preg_match("~^" . preg_quote(get_template_directory(), "~") . "~", __FILE__)) {
  wp_bootstrap_hooks();
}

Handle require when used as plugin or from template


<?php

namespace SimplyTestable\ApiBundle\Tests\Command\Stripe\Event\ProcessCommand\EventType\CustomerSubscriptionUpdated\StatusChange\TrialingToActive;

use SimplyTestable\ApiBundle\Tests\Command\Stripe\Event\ProcessCommand\EventType\CustomerSubscriptionUpdated\StatusChange\ActionStatusTest;

abstract class TrialingToActiveTest extends ActionStatusTest {

    abstract protected function getHasCard();

    public function testNotificationHasCard() {
        $this->assertNotificationBodyField('has_card', (int)$this->getHasCard());
    }

    public function testNotificationHasPlan() {
        $this->assertNotificationBodyField('plan', 'agency');
    }

    protected function getCurrentSubscriptionStatus() {
        return 'active';
    }

    protected function getPreviousSubscriptionStatus() {
        return 'trialing';
    }

    protected function getStripeEventFixturePath() {
        return $this->getFixturesDataPath() . '/../../StripeEvents/customer.subscription.updated.statuschange.json';
    }

}

<?php

namespace SimplyTestable\ApiBundle\Tests\Command\Stripe\Event\ProcessCommand\EventType\CustomerSubscriptionUpdated\StatusChange\TrialingToActive;

use SimplyTestable\ApiBundle\Tests\Command\Stripe\Event\ProcessCommand\EventType\CustomerSubscriptionUpdated\StatusChange\ActionStatusTest;

abstract class TrialingToActiveTest extends ActionStatusTest {

    abstract protected function getHasCard();

    public function testNotificationHasCard() {
        $this->assertNotificationBodyField('has_card', (int)$this->getHasCard());
    }

    protected function getCurrentSubscriptionStatus() {
        return 'active';
    }

    protected function getPreviousSubscriptionStatus() {
        return 'trialing';
    }

    protected function getStripeEventFixturePath() {
        return $this->getFixturesDataPath() . '/../../StripeEvents/customer.subscription.updated.statuschange.json';
    }

}

Include plan name in trial to active stripe event notification


<?php
namespace pharen\debug;
function convert_line_num($line_map, $errline){
    $pharen_line = 1;
    foreach($line_map as $php_line=>$ph_line){
        if($php_line >= $errline){
            $pharen_line = $ph_line;
            break;
        }
    }
    return $pharen_line;
}

function generate_pharen_err($file, $line, $msg){
    return "$msg in $file:$line\n";
}

function error_handler($errno, $errstr, $errfile, $errline, $errctx){
    $line_map = get_line_map();
    $pharen_file = basename($errfile, ".php").".phn";
    $pharen_line = convert_line_num($line_map, $errline);
    echo generate_pharen_err($pharen_file, $pharen_line, $errstr);
    return True;
}
set_error_handler('pharen\debug\error_handler');

<?php
namespace pharen\debug;
function convert_line_num($line_map, $errline){
    foreach($line_map as $php_line=>$ph_line){
        $pharen_line = $ph_line;
        if($php_line >= $errline){
            break;
        }
    }
    return $pharen_line;
}

function generate_pharen_err($file, $line, $msg){
    return "$msg in $file:$line\n";
}

function error_handler($errno, $errstr, $errfile, $errline, $errctx){
    $line_map = get_line_map();
    $pharen_file = basename($errfile, ".php").".phn";
    $pharen_line = convert_line_num($line_map, $errline);
    echo generate_pharen_err($pharen_file, $pharen_line, $errstr);
    return True;
}
set_error_handler('pharen\debug\error_handler');

Fix bug where it would default to a matching line number of 1.


@extends('layouts.app')

@section('pageTitle', 'Access Codes')

@section('content')

The Hackspace door codes and WiFi passwords

        Street Door Code

        {{ $outerDoorCode }}

        Inner Door Code

        {{ $innerDoorCode }}

        WiFi SSID

        {{ $wifiSsid }}

        WiFi PSK

        {{ $wifiPass }}

        Guest WiFi SSID

        {{ $guestWifiSsid }}

        Guest WiFi PSK

        {{ $guestWifiPass }}

@endsection

@extends('layouts.app')

@section('pageTitle', 'Access Codes')

@section('content')

                 Door Codes

Street Door

{{ $outerDoorCode }}

Inner Door

{{ $innerDoorCode }}

                 Members' WiFi

SSID

{{ $wifiSsid }}

PSK

{{ $wifiPass }}

                 Guest WiFi

SSID

{{ $guestWifiSsid }}

PSK

{{ $guestWifiPass }}

@endsection

Rework layout of access codes page

Rework layout of access codes page


<?php

abstract class AlgorithmMM extends Algorithm {

    /**
     * Origianl graph
     *
     * @var Graph
     */
    protected $graph;

    /**
     * The given graph where the algorithm should operate on
     *
     * @param Graph $graph
     * @throws Exception if the given graph is not balanced
     */
    public function __construct(Graph $graph){
        $this->graph = $graph;
    }

    /**
     * Get the count of edges that are in the matchin
     *
     * @throws Exception
     * @return AlgorithmMCF $this (chainable)
     */
    public function getMatchingValue(){
        // TODO count the matching edges

        return null;
    }

    /**
     * create new resulting graph with minimum-cost flow on edges
     *
     * @throws Exception if the graph has not enough capacity for the minimum-cost flow
     * @return Graph
     */
    abstract public function createGraph();
}

<?php

abstract class AlgorithmMM extends Algorithm {

    /**
     * Origianl graph
     *
     * @var Graph
     */
    protected $graph;

    /**
     * The given graph where the algorithm should operate on
     *
     * @param Graph $graph
     * @throws Exception if the given graph is not balanced
     */
    public function __construct(Graph $graph){
        $this->graph = $graph;
    }

    /**
     * Get the count of edges that are in the match
     *
     * @throws Exception
     * @return AlgorithmMCF $this (chainable)
     * @uses AlgorithmMM::createGraph()
     * @uses Graph::getNumberOfEdges()
     */
    public function getNumberOfMatches(){
        return $this->createGraph()->getNumberOfEdges();
    }

    /**
     * create new resulting graph with minimum-cost flow on edges
     *
     * @throws Exception if the graph has not enough capacity for the minimum-cost flow
     * @return Graph
     */
    abstract public function createGraph();
}

Add helper method to count number of matches


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

/**
 * A form input of type text, password
 *
 * @author pyd <pierre.yves.delettre@gmail.com>
 */
class TextInput extends \pyd\testkit\web\base\ElementWrapper
{
    /**
     * @return string the input value
     */
    public function getValue()
    {
        return $this->getAttribute('value');
    }

    /**
     * @param string $value the input value
     */
    public function setValue($value)
    {
        $this->setAttribute('value', $value);
    }
}

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

use yii\base\InvalidCallException;

/**
 * A form input of type text, password
 *
 * @author pyd <pierre.yves.delettre@gmail.com>
 */
class TextInput extends \pyd\testkit\web\base\ElementWrapper
{
    /**
     * @return string the input value
     */
    public function getValue()
    {
        return $this->getAttribute('value');
    }

    /**
     * @param string $value the input value
     */
    public function setValue($value)
    {
        $this->setAttribute('value', $value);
    }

    /**
     * @throws InvalidCallException
     */
    public function getText()
    {
        throw new InvalidCallException("Method " . __METHOD__ . " is not "
                . "available for a text input element. Use getValue() instead.");
    }
}

Disable getText() method for text input element. Use getValue() instead.


<?php

namespace CassandraPDO4Doctrine\tests;

use CassandraPDO4Doctrine\Doctrine\DBAL\DriverManager;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\Setup;

class CP4DBaseTestCase extends \PHPUnit_Framework_TestCase {

    static protected function _getDataDir() {
        return realpath(__DIR__ . '/../data');
    }

    static public function setUpBeforeClass() {
        $D = self::_getDataDir();
        system("cqlsh < {$D}/db_create.cql3");
    }

    static public function tearDownAfterClass() {
        $D = self::_getDataDir();
        system("cqlsh < {$D}/db_drop.cql3");
    }

    public function setUp() {
        $D = self::_getDataDir();
        system("cqlsh < {$D}/db_data.cql3");
    }

    /**
     * @return EntityManager
     * @throws \Doctrine\ORM\ORMException
     */
    public function getEntityManager() {

        $paths = array(__DIR__ . "/entity/");
        $isDevMode = true;

        // the connection configuration
        $dbParams = array(
            'driver'   => 'pdo_cassandra',
            'user'     => $GLOBALS['DB_USER'],
            'password' => $GLOBALS['DB_PASSWD'],
            'dbname'   => $GLOBALS['DB_DBNAME'],
        );

        $config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode,null,null,false);

        $conn = DriverManager::getConnection($dbParams,$config);

        $entityManager = EntityManager::create($conn, $config);
        return $entityManager;
    }

}

<?php

namespace CassandraPDO4Doctrine\tests;

use CassandraPDO4Doctrine\Doctrine\DBAL\DriverManager;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\Setup;

class CP4DBaseTestCase extends \PHPUnit_Framework_TestCase {

    static protected function _getDataDir() {
        return realpath(__DIR__ . '/../data');
    }

    static public function setUpBeforeClass() {
        $D = self::_getDataDir();
        system("cqlsh < {$D}/db_create.cql3");
    }

    static public function tearDownAfterClass() {
        $D = self::_getDataDir();
        system("cqlsh < {$D}/db_drop.cql3");
    }

    public function setUp() {
        $D = self::_getDataDir();
        system("cqlsh < {$D}/db_data.cql3");
    }

    /**
     * @return EntityManager
     * @throws \Doctrine\ORM\ORMException
     */
    public function getEntityManager() {

        $paths = array(__DIR__ . "/entity/");
        $isDevMode = true;

        // the connection configuration
        $dbParams = array(
            'driver'   => 'pdo_cassandra',
            'host'     => 'localhost',
            'port'     => '9160',
            'cqlversion' => '3.0.0',
            'user'     => $GLOBALS['DB_USER'],
            'password' => $GLOBALS['DB_PASSWD'],
            'dbname'   => $GLOBALS['DB_DBNAME'],
        );

        $config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode,null,null,false);

        $conn = DriverManager::getConnection($dbParams,$config);

        $entityManager = EntityManager::create($conn, $config);
        return $entityManager;
    }

}

FIX tests: add connection parameters

FIX tests: add connection parameters


<?php

namespace Enhavo\Bundle\ShopBundle\Block;

use Enhavo\Bundle\BlockBundle\Model\BlockInterface;
use Enhavo\Bundle\ShopBundle\Entity\ProductListBlock;
use Enhavo\Bundle\ShopBundle\Factory\ProductListBlockFactory;
use Enhavo\Bundle\ShopBundle\Form\Type\ProductListBlockType as ProductListBlockFormType;
use Enhavo\Bundle\BlockBundle\Block\AbstractBlockType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ProductListBlockType extends AbstractBlockType
{
    public function createViewData(BlockInterface $block, $resource, array $options)
    {
        $data = parent::createViewData($block, $resource, $options);
        $data['products'] = $this->container->get('sylius.repository.product')->findAll();
        return $data;
    }

    public function configureOptions(OptionsResolver $optionsResolver)
    {
        parent::configureOptions($optionsResolver);

        $optionsResolver->setDefaults([
            'model' => ProductListBlock::class,
            'parent' => ProductListBlock::class,
            'form' => ProductListBlockFormType::class,
            'factory' => ProductListBlockFactory::class,
            'repository' => 'ProductListBlock::class',
            'template' => 'theme/block/product-list.html.twig',
            'label' => 'ProductList',
            'translationDomain' => 'EnhavoShopBundle',
            'groups' => ['default', 'content']
        ]);
    }

    public function getType()
    {
        return 'shop_product_list';
    }
}

<?php

namespace Enhavo\Bundle\ShopBundle\Block;

use Enhavo\Bundle\BlockBundle\Model\BlockInterface;
use Enhavo\Bundle\ShopBundle\Entity\ProductListBlock;
use Enhavo\Bundle\ShopBundle\Factory\ProductListBlockFactory;
use Enhavo\Bundle\ShopBundle\Form\Type\ProductListBlockType as ProductListBlockFormType;
use Enhavo\Bundle\BlockBundle\Block\AbstractBlockType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ProductListBlockType extends AbstractBlockType
{
    public function createViewData(BlockInterface $block, $resource, array $options)
    {
        $data = parent::createViewData($block, $resource, $options);
        $data['products'] = $this->container->get('sylius.repository.product')->findAll();
        return $data;
    }

    public function configureOptions(OptionsResolver $optionsResolver)
    {
        parent::configureOptions($optionsResolver);

        $optionsResolver->setDefaults([
            'model' => ProductListBlock::class,
            'parent' => ProductListBlock::class,
            'form' => ProductListBlockFormType::class,
            'factory' => ProductListBlockFactory::class,
            'repository' => 'ProductListBlock::class',
            'template' => 'theme/block/product-list.html.twig',
            'label' => 'ProductList',
            'translation_domain' => 'EnhavoShopBundle',
            'groups' => ['default', 'content']
        ]);
    }

    public function getType()
    {
        return 'shop_product_list';
    }
}

Use Component/Type and PolyCollectionType for blocks


<?php
/**
 * This file is part of the BEAR.Sunday package.
 *
 * @license http://opensource.org/licenses/MIT MIT
 */
namespace BEAR\Sunday\Provide\Transfer;

use BEAR\Resource\ResourceObject;
use BEAR\Sunday\Extension\Transfer\TransferInterface;

class HttpResponder implements TransferInterface
{
    /**
     * {@inheritdoc}
     */
    public function __invoke(ResourceObject $resourceObject, array $server)
    {
        unset($server);
        // render
        if (! $resourceObject->view) {
            $resourceObject->toString();
        }

        // code
        http_response_code($resourceObject->code);

        // header
        foreach ($resourceObject->headers as $label => $value) {
            header("{$label}: {$value}", false);
        }

        // body
        echo $resourceObject->view;
    }
}

<?php
/**
 * This file is part of the BEAR.Sunday package.
 *
 * @license http://opensource.org/licenses/MIT MIT
 */
namespace BEAR\Sunday\Provide\Transfer;

use BEAR\Resource\ResourceObject;
use BEAR\Sunday\Extension\Transfer\TransferInterface;

class HttpResponder implements TransferInterface
{
    /**
     * {@inheritdoc}
     */
    public function __invoke(ResourceObject $resourceObject, array $server)
    {
        unset($server);
        // render
        if (! $resourceObject->view) {
            $resourceObject->toString();
        }

        // header
        foreach ($resourceObject->headers as $label => $value) {
            header("{$label}: {$value}", false);
        }

        // code
        http_response_code($resourceObject->code);

        // body
        echo $resourceObject->view;
    }
}

Allow the `WWW-Authenticate` header field in other response than 401.

Passing `WWW-Authenticate` to `header()` overwrites the status code to 401.

https://github.com/php/php-src/blob/a51cb393b1accc29200e8f57ef867a6a47b2564f/ain/SAPI.c#L829

According to RFC it is said that it is also possible to include `WWW-Authenticate` in status codes other than 401.

https://tools.ietf.org/html/rfc7235#page-7

> A server MAY generate a WWW-Authenticate header field in other response.

Since OAuth 2.0 Bearer writes its contents in `WWW-Authenticate` header even for errors other than 401, the original status code is applied after the status code reaches 401 by inserting the `WWW-Authenticate` header field is necessary.

https://tools.ietf.org/html/rfc6750#page-9


<?php
#
# Copyright (c) 2000-2013 University of Utah and the Flux Group.
#
# {{{EMULAB-LICENSE
#
# This file is part of the Emulab network testbed software.
#
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
#
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
#
# }}}
#
require("defs.php3");

#
# Verify page arguments.
#
$optargs = OptionalPageArguments("submit",      PAGEARG_STRING,
				 "query",       PAGEARG_STRING);

if (!isset($query) || $query == "Search Documentation") {
    $query = "";
}
header("Location: http://wiki.emulab.net/@@search?SearchableText=$query");

?>

<?php
#
# Copyright (c) 2000-2013 University of Utah and the Flux Group.
#
# {{{EMULAB-LICENSE
#
# This file is part of the Emulab network testbed software.
#
# This file is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or (at
# your option) any later version.
#
# This file is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
# License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this file.  If not, see <http://www.gnu.org/licenses/>.
#
# }}}
#
require("defs.php3");

#
# Verify page arguments.
#
$optargs = OptionalPageArguments("submit",      PAGEARG_STRING,
				 "query",       PAGEARG_STRING);

if (!isset($query) || $query == "Search Documentation") {
    $query = "";
}
else {
    $query = urldecode($query);
    $query = preg_replace("/[\ ]+/", "+", $query);
}
header("Location: http://wiki.emulab.net/@@search?SearchableText=$query");

?>

Send the query over to plone in the proper format.


<?php

class Shift extends BaseRow {

	public $table_name = 'shifts';

	function validate () {
		$errors = array();
		if (empty($this->start_time))
			$errors['start_time'] = 'Start time must be specified.';
		if (empty($this->end_time))
			$errors['end'] = 'End time must be specified.';
		return $errors;
	}
}

function ShiftTable () {
	return new Shift();
}

?>

<?php

class Shift extends BaseRow {

	public $table_name = 'shifts';

	function validate () {
		$errors = array();
		if (empty($this->start_time))
			$errors['start_time'] = 'Start time must be specified.';
		if (empty($this->end_time))
			$errors['end'] = 'End time must be specified.';
		return $errors;
	}

	function concurrentShifts () {

		$shifts = $this->find(array(
			'where' => 'ID <> ?',
			'params' => array($this->id)
		));

		$concurrent_shifts = array();
		foreach ($shifts as $shift) {

			// Two time periods overlap if the first
			// starts before the second ends, and ends
			// after the second starts.
			if (($shift->start_time < $this->end_time) && ($shift->end_time > $this->start_time))
				$concurrent_shifts[] = $shift;
		}

		return $concurrent_shifts;
	}
}

function ShiftTable () {
	return new Shift();
}

?>

Add function to find concurrent shifts.

Add function to find concurrent shifts.


<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Third Party Services
    |--------------------------------------------------------------------------
    |
    | This file is for storing the credentials for third party services such
    | as Mailgun, Postmark, AWS and more. This file provides the de facto
    | location for this type of information, allowing packages to have
    | a conventional file to locate the various service credentials.
    |
    */

    'mailgun' => [
        'domain' => env('MAILGUN_DOMAIN'),
        'secret' => env('MAILGUN_SECRET'),
        'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
    ],

    'postmark' => [
        'token' => env('POSTMARK_TOKEN'),
    ],

    'ses' => [
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
    ],

    'steam' => [
        'client_id' => null,
        'client_secret' => null,
        'redirect' => env('APP_URL').'/auth/steam/callback',
        'api_key' => env('STEAM_API_KEY'),
    ],

];

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Third Party Services
    |--------------------------------------------------------------------------
    |
    | This file is for storing the credentials for third party services such
    | as Mailgun, Postmark, AWS and more. This file provides the de facto
    | location for this type of information, allowing packages to have
    | a conventional file to locate the various service credentials.
    |
    */

    'mailgun' => [
        'domain' => env('MAILGUN_DOMAIN'),
        'secret' => env('MAILGUN_SECRET'),
        'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
    ],

    'postmark' => [
        'token' => env('POSTMARK_TOKEN'),
    ],

    'ses' => [
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
    ],

    'steam' => [
        'client_id' => null,
        'client_secret' => null,
        'redirect' => env('APP_URL').'auth/steam/callback',
        'api_key' => env('STEAM_API_KEY'),
    ],

];

Remove slash already present in APP_URL

Remove slash already present in APP_URL


<?php

namespace React\Promise\Internal;

use Exception;
use LogicException;
use React\Promise\PromiseAdapter\CallbackPromiseAdapter;
use React\Promise\PromiseTest\PromiseRejectedTestTrait;
use React\Promise\PromiseTest\PromiseSettledTestTrait;
use React\Promise\TestCase;

class RejectedPromiseTest extends TestCase
{
    use PromiseSettledTestTrait,
        PromiseRejectedTestTrait;

    public function getPromiseTestAdapter(callable $canceller = null)
    {
        $promise = null;

        return new CallbackPromiseAdapter([
            'promise' => function () use (&$promise) {
                if (!$promise) {
                    throw new LogicException('RejectedPromise must be rejected before obtaining the promise');
                }

                return $promise;
            },
            'resolve' => function () {
                throw new LogicException('You cannot call resolve() for React\Promise\RejectedPromise');
            },
            'reject' => function ($reason = null) use (&$promise) {
                if (!$promise) {
                    $promise = new RejectedPromise($reason);
                }
            },
            'settle' => function ($reason = null) use (&$promise) {
                if (!$promise) {
                    if (!$reason instanceof Exception) {
                        $reason = new Exception($reason);
                    }

                    $promise = new RejectedPromise($reason);
                }
            },
        ]);
    }
}

<?php

namespace React\Promise\Internal;

use Exception;
use LogicException;
use React\Promise\PromiseAdapter\CallbackPromiseAdapter;
use React\Promise\PromiseTest\PromiseRejectedTestTrait;
use React\Promise\PromiseTest\PromiseSettledTestTrait;
use React\Promise\TestCase;

class RejectedPromiseTest extends TestCase
{
    use PromiseSettledTestTrait,
        PromiseRejectedTestTrait;

    public function getPromiseTestAdapter(callable $canceller = null)
    {
        $promise = null;

        return new CallbackPromiseAdapter([
            'promise' => function () use (&$promise) {
                if (!$promise) {
                    throw new LogicException('RejectedPromise must be rejected before obtaining the promise');
                }

                return $promise;
            },
            'resolve' => function () {
                throw new LogicException('You cannot call resolve() for React\Promise\RejectedPromise');
            },
            'reject' => function ($reason = null) use (&$promise) {
                if (!$promise) {
                    $promise = new RejectedPromise($reason);
                }
            },
            'settle' => function ($reason = "") use (&$promise) {
                if (!$promise) {
                    if (!$reason instanceof Exception) {
                        $reason = new Exception($reason);
                    }

                    $promise = new RejectedPromise($reason);
                }
            },
        ]);
    }
}

Fix incorrect default message for exception ctor

PHP8.1+ complains about Exception not accepting `null` as the message
argument for an `Exception` constructor. This fixes it.


<?php

/**
 * Config for the connections for the test
 */
return [
    'mysql' => [
        'type'     => 'mysql',
        'host'     => 'localhost',
        'database' => 'sample_database',
        'user'     => 'sample_user',
        'password' => 'sample_password',
        'charset'  => 'utf8',
        'options'  => [
            PDO::ATTR_PERSISTENT         => true,
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
        ],
    ],

    'pgsql' => [
        'type'     => 'pgsql',
        'host'     => 'localhost',
        'database' => 'sample_database',
        'user'     => 'sample_user',
        'password' => 'sample_password',
        'options'  => [
            PDO::ATTR_PERSISTENT         => true,
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
        ],
    ]
];

<?php

/**
 * Config for the connections for the test
 */
return [
    'mysql' => [
        'type'     => 'mysql',
        'host'     => 'localhost',
        'database' => 'sample_database',
        'user'     => 'sample_user',
        'password' => 'sample_password',
        'charset'  => 'utf8',
        'options'  => [
            PDO::ATTR_PERSISTENT         => true,
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
        ],
        'class' => \OlajosCs\QueryBuilder\MySQL\Connection::class // Needed only for testing
    ],

    'pgsql' => [
        'type'     => 'pgsql',
        'host'     => 'localhost',
        'database' => 'sample_database',
        'user'     => 'sample_user',
        'password' => 'sample_password',
        'options'  => [
            PDO::ATTR_PERSISTENT         => true,
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
        ],
        'class' => \OlajosCs\QueryBuilder\MySQL\Connection::class // Needed only for testing
    ]
];

Put classes into config file

Put classes into config file


<?php
	use Symfony\Component\HttpFoundation\Response;
	use Symfony\Component\HttpFoundation\Request;
	require_once '../vendor/autoload.php';

	$app = new Silex\Application();
	$app->register(new Silex\Provider\SessionServiceProvider());
	$app->register(new Silex\Provider\DoctrineServiceProvider(), array(
			'db.options' => array(
					'driver'    => 'pdo_mysql',
					'host'      => 'localhost',
					'dbname'    => 'gumball',
					'user'      => 'root',
					'password'  => 'root',
					'charset'   => 'utf8mb4',
				),
		));
	$app['debug'] = true;
	$app['dir'] = dirname(__DIR__);
	$app['basePath'] = dirname(__DIR__);
	$app['dir_repo'] = "/var/www/";

	Request::enableHttpMethodParameterOverride();
	$app->mount('/', new Core\Controller());

	$app->error(function (\Exception $e, $code) {
		switch ($code) {
				case 404:
					$message = '

Ops, nada aqui!

								';
				break;
			default:
				$message = $e->getMessage() . $code;
		}
		return new Response($message);
	});
	$app->run();

<?php
	use Symfony\Component\HttpFoundation\Response;
	use Symfony\Component\HttpFoundation\Request;
	require_once '../vendor/autoload.php';

	$app = new Silex\Application();
	$app->register(new Silex\Provider\SessionServiceProvider());
	$app->register(new Silex\Provider\DoctrineServiceProvider(), array(
			'db.options' => array(
					'driver'    => 'pdo_mysql',
					'host'      => 'localhost',
					'dbname'    => 'gumball',
					'user'      => 'root',
					'password'  => '',
					'charset'   => 'utf8mb4',
				),
		));
	$app['debug'] = true;
	$app['dir'] = dirname(__DIR__);
	$app['basePath'] = dirname(__DIR__);

	if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
		$app['dir_repo'] = "c:/wamp/www/";
	else
		$app['dir_repo'] = "/var/www/";

	Request::enableHttpMethodParameterOverride();
	$app->mount('/', new Core\Controller());

	$app->error(function (\Exception $e, $code) {
		switch ($code) {
				case 404:
					$message = '

Ops, nada aqui!

								';
				break;
			default:
				$message = $e->getMessage() . $code;
		}
		return new Response($message);
	});
	$app->run();

Add verificacao de tipo de SO

Add verificacao de tipo de SO


<?php
class EmailValidator {
	private $model;

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

	public function validate ($property, $rules) {
		if (!empty($this->model->$property)) {
			if (preg_match('/^\A[^\s@]+@[^\s.@][^\s@]*\.[^\s@]+$/ui', $this->model->$property) != 1) {
				return array('email' => $rules['name']);
			}
		}

		return ValidationHelper::validateLength(mb_strlen($this->model->$property), $rules);
	}
}
?>

<?php
class EmailValidator {
	private $model;

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

	public function validate ($property, $rules) {
		if (!empty($this->model->$property)) {
			if (preg_match('/^\A[^\s"(),:;<>\[\]\\\@]+@[^\s.@][^\s@]*\.[^\s@]+$/ui', $this->model->$property) != 1) {
				return array('email' => $rules['name']);
			}
		}

		return ValidationHelper::validateLength(mb_strlen($this->model->$property), $rules);
	}
}
?>

Make email validation a bit stricter again

This expands the email validation somewhat, adding characters that can
only be used within a quoted part of an email address to the illegal
characters in the local part of the address. These are characters like
backslash, square brackets, parenthesis etc. which in general nobody use
or should use.


@extends('components.content-area')

@section('content')

"{{ $faker->paragraph(3) }}"

{{ $faker->words(2, true) }}

{{ $faker->paragraph(10) }}

{{ $faker->paragraph(10) }}

{{ $faker->paragraph(10) }}

@endsection

Add left and right margin for spacing

Add left and right margin for spacing


<?php

namespace ActiveCollab\DateValue;

use Carbon\Carbon;

/**
 * @package ActiveCollab\DateValue
 */
class DateValue extends Carbon implements DateValueInterface
{
}

<?php

namespace ActiveCollab\DateValue;

use Carbon\Carbon;

/**
 * @package ActiveCollab\DateValue
 */
class DateValue extends Carbon implements DateValueInterface
{
    /**
     * Create a new DateValue instance.
     *
     * @param string              $time
     * @param \DateTimeZone|string $tz
     */
    public function __construct($time = null, $tz = null)
    {
        if (empty($tz)) {
            $tz = 'UTC';
        }

        parent::__construct($time, $tz);
    }
}

Make sure that we always use UTC when working with dates


<?php

error_reporting(E_ALL | E_STRICT);

date_default_timezone_set('UTC');

mb_language('uni');
mb_regex_encoding('UTF-8');
mb_internal_encoding('UTF-8');

require_once __DIR__ . '/integration/resources/ORMTestCase.php';

<?php

error_reporting(E_ALL | E_STRICT);

date_default_timezone_set('UTC');

mb_language('uni');
mb_regex_encoding('UTF-8');
mb_internal_encoding('UTF-8');

require_once dirname(__DIR__) . '/vendor/autoload.php';
require_once __DIR__ . '/integration/resources/ORMTestCase.php';

Add an include to the autoloader.

Add an include to the autoloader.


<?php

namespace Tests;

use Illuminate\Contracts\Console\Kernel;

trait CreatesApplication
{
    /**
     * Creates the application.
     *
     * @return \Illuminate\Foundation\Application
     */
    public function createApplication()
    {
        $app = require __DIR__.'/../bootstrap/app.php';

        $app->loadEnvironmentFrom('.env.testing');

        $app->make(Kernel::class)->bootstrap();

        return $app;
    }
}

<?php

namespace Tests;

use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\Hash;

trait CreatesApplication
{
    /**
     * Creates the application.
     *
     * @return \Illuminate\Foundation\Application
     */
    public function createApplication()
    {
        $app = require __DIR__.'/../bootstrap/app.php';

        $app->loadEnvironmentFrom('.env.testing');

        $app->make(Kernel::class)->bootstrap();

        Hash::setRounds(5);

        return $app;
    }
}

Set rounds to 5 in tests

Hash: Set rounds to 5 in tests