<?php

declare(strict_types=1);

namespace AugustOffensive\model;

/**
 * Model connection class for connecting to database via PDO.
 */
class Connection
{
    /** @var PDO $_conn PDO connection to database. */
    private $_conn;
    /**
     * Initiates connection to PostGreSQL database.
     *
     * @return Connection
     */
    public function __construct ()
    {
        // Establish connection to db
        include './creds.php';

        try {
	        $_conn = new PDO(
                "pgsql: host=" . $cred->getHost() .
                    (($cred->getPort() !== '') ? ";port=" . $cred->getPort() : '') .
                    ";dbname=" . $cred->getDBName(),
                $cred->getLogin(),
                $cred->getPassword()
            );
            // we destroy $cred as quickly as possible
            $cred = null;
        } catch (PDOException as $e) {
            // we destroy $cred as quickly as possible
            $cred = null;
            die(json_encode(array("Result-Type" => "Error", "Content" => array($e))));
        }
    }
}

<?php

declare(strict_types=1);

namespace AugustOffensive\model;

/**
 * Model connection class for connecting to database via PDO.
 */
class Connection
{
    /** @var PDO $_conn PDO connection to database. */
    private $_conn;
    /**
     * Initiates connection to PostGreSQL database.
     *
     * @return Connection
     */
    public function __construct ()
    {
        // Establish connection to db
        include './creds.php';

        try {
	        $_conn = new PDO(
                "pgsql: host=" . $cred->getHost() .
                    (($cred->getPort() !== '') ? ";port=" . $cred->getPort() : '') .
                    ";dbname=" . $cred->getDBName(),
                $cred->getLogin(),
                $cred->getPassword()
            );
            // we destroy $cred as quickly as possible
            $cred = null;
        } catch (PDOException $e) {
            // we destroy $cred as quickly as possible
            $cred = null;
            die(json_encode(array("Result-Type" => "Error", "Content" => array($e))));
        }
    }
}

Remove unexpected keyword from statement


<?php
declare (strict_types = 1);

namespace GrottoPress\Jentil\Setups\Customizer\Layout\Settings;

use GrottoPress\Jentil\Setups\Customizer\Layout\Layout;
use GrottoPress\Jentil\utilities\ThemeMods\Layout as LayoutMod;
use GrottoPress\Jentil\Setups\Customizer\AbstractSetting as Setting;

abstract class AbstractSetting extends Setting
{
    /**
     * @var LayoutMod
     */
    protected $themeMod;

    public function __construct(Layout $layout)
    {
        parent::__construct($layout);

        $this->args['sanitize_callback'] = 'sanitize_title';

        $this->control['section'] = $this->section->id;
        $this->control['label'] = \esc_html__('Select layout', 'jentil');
        $this->control['type'] = 'select';
        $this->control['choices'] = $this->section->customizer->app
            ->utilities->page->layouts->IDs();
    }

    protected function themeMod(array $args): LayoutMod
    {
        return $this->section->customizer->app->utilities->themeMods->layout(
            $args
        );
    }
}

<?php
declare (strict_types = 1);

namespace GrottoPress\Jentil\Setups\Customizer\Layout\Settings;

use GrottoPress\Jentil\Setups\Customizer\Layout\Layout;
use GrottoPress\Jentil\Utilities\ThemeMods\Layout as LayoutMod;
use GrottoPress\Jentil\Setups\Customizer\AbstractSetting as Setting;

abstract class AbstractSetting extends Setting
{
    /**
     * @var LayoutMod
     */
    protected $themeMod;

    public function __construct(Layout $layout)
    {
        parent::__construct($layout);

        $this->args['sanitize_callback'] = 'sanitize_title';

        $this->control['section'] = $this->section->id;
        $this->control['label'] = \esc_html__('Select layout', 'jentil');
        $this->control['type'] = 'select';
        $this->control['choices'] = $this->section->customizer->app
            ->utilities->page->layouts->IDs();
    }

    protected function themeMod(array $args): LayoutMod
    {
        return $this->section->customizer->app->utilities->themeMods->layout(
            $args
        );
    }
}

Fix wrong letter case in namespace

Fix wrong letter case in namespace


<?php defined('SYSPATH') or die('No direct access allowed.');
/**
 * View fix for exceptions
 *
 * @package    Anqh
 * @author     Antti Qvickström
 * @copyright  (c) 2010 Antti Qvickström
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 */
class Anqh_View extends Kohana_View {

	/**
	 * Magic method, returns the output of [View::render].
	 *
	 * @return  string
	 * @uses    View::render
	 */
	public function __toString() {
		try {
			return $this->render();
		} catch (Exception $e) {

			// Display the exception message only if not in production
			ob_start();
			Kohana::exception_handler($e);

			if (Kohana::$environment == Kohana::PRODUCTION) {
				ob_end_clean();
				echo __('An error occured and has been logged.');
			} else {
				echo ob_get_clean();
			}

			return '';
		}
	}

}

<?php defined('SYSPATH') or die('No direct access allowed.');
/**
 * View fix for exceptions
 *
 * @package    Anqh
 * @author     Antti Qvickström
 * @copyright  (c) 2010 Antti Qvickström
 * @license    http://www.opensource.org/licenses/mit-license.php MIT license
 */
class Anqh_View extends Kohana_View {

	/**
	 * Magic method, returns the output of [View::render].
	 *
	 * @return  string
	 * @uses    View::render
	 */
	public function __toString() {
		try {
			return $this->render();
		} catch (Exception $e) {

			// Display the exception message only if not in production
			ob_start();
			Kohana::exception_handler($e);

			if (Kohana::$environment == Kohana::PRODUCTION) {
				ob_end_clean();
				return __('An error occured and has been logged.');
			} else {
				return ob_get_clean();
			}
		}
	}

}

Return exception test instead of printing


<?php namespace LaurentEsc\Localization;

use Illuminate\Support\ServiceProvider;

class LocalizationServiceProvider extends ServiceProvider
{

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__ . '/../../config/config.php' => config_path('localization.php'),
        ], 'config');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {

        $packageConfigFile = __DIR__ . '/../config/config.php';
        $this->mergeConfigFrom(
            $packageConfigFile, 'localization'
        );

        $this->app['localization.localize'] = $this->app->share(
            function () {
                return new Localize();
            }
        );

        $this->app['localization.router'] = $this->app->share(
            function () {
                return new Router();
            }
        );

    }

}

<?php namespace LaurentEsc\Localization;

use Illuminate\Support\ServiceProvider;

class LocalizationServiceProvider extends ServiceProvider
{

    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__ . '/../config/config.php' => config_path('localization.php'),
        ], 'config');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {

        $packageConfigFile = __DIR__ . '/../config/config.php';
        $this->mergeConfigFrom(
            $packageConfigFile, 'localization'
        );

        $this->app['localization.localize'] = $this->app->share(
            function () {
                return new Localize();
            }
        );

        $this->app['localization.router'] = $this->app->share(
            function () {
                return new Router();
            }
        );

    }

}

Fix a problem with config publishing

Fix a problem with config publishing


<?php

/*
 * This file is part of the Symfony CMF package.
 *
 * (c) 2011-2015 Symfony CMF
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Cmf\Component\Resource;

use Symfony\Cmf\Component\Resource\Puli\Api\ResourceRepository;

/**
 * The registry is used to retrieve named repositories.
 *
 * @author Daniel Leech <daniel@dantleech.com>
 *
 * @internal
 */
interface RepositoryRegistryInterface
{
    /**
     * Return the names of all the regstered repositories.
     *
     * @return string[]
     */
    public function names();

    /**
     * Return all repositories.
     *
     * Keys must be the repository names.
     *
     * @return ResourceRepository[]
     */
    public function all();

    /**
     * Return the named repository.
     *
     * @param string $name
     *
     * @return ResourceRepository
     */
    public function get($repositoryName);

    /**
     * Return the name assigned to the given resource repository.
     *
     * @return string
     *
     * @throws \RuntimeException If the name cannot be determined
     */
    public function getRepositoryName(ResourceRepository $resource);

    /**
     * Return the type for the given resource repository.
     *
     * @return string
     *
     * @throws \RuntimeException If the resource repository is not mapped
     */
    public function getRepositoryType(ResourceRepository $resource);
}

<?php

/*
 * This file is part of the Symfony CMF package.
 *
 * (c) 2011-2015 Symfony CMF
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Cmf\Component\Resource;

use Symfony\Cmf\Component\Resource\Puli\Api\ResourceRepository;

/**
 * The registry is used to retrieve named repositories.
 *
 * @author Daniel Leech <daniel@dantleech.com>
 *
 * @internal
 */
interface RepositoryRegistryInterface
{
    /**
     * Return the names of all the registered repositories.
     *
     * @return string[]
     */
    public function names();

    /**
     * Return all repositories.
     *
     * Keys must be the repository names.
     *
     * @return ResourceRepository[]
     */
    public function all();

    /**
     * Return the named repository.
     *
     * @param null|string $name
     *
     * @return ResourceRepository
     */
    public function get($repositoryName = null);

    /**
     * Return the name assigned to the given resource repository.
     *
     * @return string
     *
     * @throws \RuntimeException If the name cannot be determined
     */
    public function getRepositoryName(ResourceRepository $resource);

    /**
     * Return the type for the given resource repository.
     *
     * @return string
     *
     * @throws \RuntimeException If the resource repository is not mapped
     */
    public function getRepositoryType(ResourceRepository $resource);
}

Allow passing null to get() to get the default repository


<?php

namespace SwaggerGen\Swagger\Type;

/**
 * Basic file type definition.
 *
 * @package    SwaggerGen
 * @author     Martijn van der Lee <martijn@vanderlee.com>
 * @copyright  2014-2015 Martijn van der Lee
 * @license    https://opensource.org/licenses/MIT MIT
 */
class FileType extends AbstractType
{

	protected function parseDefinition($definition)
	{
		$type = strtolower($definition);

		$parent = $this->getParent();
		if (!($parent instanceof \SwaggerGen\Swagger\Parameter) || !$parent->isForm()) {
			throw new \SwaggerGen\Exception("File type only allowed on form parameter: '{$definition}'");
		}

		$consumes = $this->getParentClass('\SwaggerGen\Swagger\Operation')->getConsumes();
		if (empty($consumes)) {
			$consumes = $this->getRoot()->getConsumes();
		}

		if ($consumes !== array('multipart/form-data') && $consumes !== array('application/x-www-form-urlencoded')) {
			throw new \SwaggerGen\Exception("File type without valid consume: '{$definition}'");
		}
	}

	public function toArray()
	{
		return self::array_filter_null([
					'type' => 'file',
		]);
	}

	public function __toString()
	{
		return __CLASS__;
	}

}

<?php

namespace SwaggerGen\Swagger\Type;

/**
 * Basic file type definition.
 *
 * @package    SwaggerGen
 * @author     Martijn van der Lee <martijn@vanderlee.com>
 * @copyright  2014-2015 Martijn van der Lee
 * @license    https://opensource.org/licenses/MIT MIT
 */
class FileType extends AbstractType
{

	protected function parseDefinition($definition)
	{
		$type = strtolower($definition);

		$parent = $this->getParent();
		if (!($parent instanceof \SwaggerGen\Swagger\Parameter) || !$parent->isForm()) {
			throw new \SwaggerGen\Exception("File type '{$definition}' only allowed on form parameter");
		}

		$consumes = $this->getParentClass('\SwaggerGen\Swagger\Operation')->getConsumes();
		if (empty($consumes)) {
			$consumes = $this->getRoot()->getConsumes();
		}

		$valid_consumes = ((int) in_array('multipart/form-data', $consumes)) + ((int) in_array('application/x-www-form-urlencoded', $consumes));
		if (empty($consumes) || $valid_consumes !== count($consumes)) {
			throw new \SwaggerGen\Exception("File type '{$definition}' without valid consume");
		}
	}

	public function toArray()
	{
		return self::array_filter_null([
					'type' => 'file',
		]);
	}

	public function __toString()
	{
		return __CLASS__;
	}

}

Fix up consume either/both check

Fix up consume either/both check


<?php
/**
 * @author    Lev Semin <lev@darvin-studio.ru>
 * @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\AdminBundle\Security\OAuth\Exception;

use Darvin\AdminBundle\Security\OAuth\Response\DarvinAuthResponse;

/**
 * Bad response exception
 */
class BadResponseException extends \LogicException
{
    private $needClass;
    private $getClass;

    /**
     * BadResponseException constructor.
     *
     * @param object $object    Object
     * @param string $needClass Need class
     */
    public function __construct($object, $needClass = null)
    {
        $this->needClass = $needClass;
        $this->getClass = is_object($object) ? get_class($object) : 'not object';

        if ($needClass == null) {
            $this->needClass = DarvinAuthResponse::DARVIN_AUTH_RESPONSE_CLASS;
        }

        parent::__construct(sprintf(
            "OAuth response must be instance of %s, %s given",
            $this->needClass,
            $this->getClass
        ));
    }

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

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

<?php
/**
 * @author    Lev Semin <lev@darvin-studio.ru>
 * @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\AdminBundle\Security\OAuth\Exception;

use Darvin\AdminBundle\Security\OAuth\Response\DarvinAuthResponse;

/**
 * Bad response exception
 */
class BadResponseException extends \LogicException
{
    private $needClass;
    private $getClass;

    /**
     * BadResponseException constructor.
     *
     * @param object $object    Object
     * @param string $needClass Need class
     */
    public function __construct($object, $needClass = null)
    {
        $this->needClass = $needClass;
        $this->getClass = is_object($object) ? get_class($object) : 'not object';

        if (empty($needClass)) {
            $this->needClass = DarvinAuthResponse::DARVIN_AUTH_RESPONSE_CLASS;
        }

        parent::__construct(sprintf(
            "OAuth response must be instance of %s, %s given",
            $this->needClass,
            $this->getClass
        ));
    }

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

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

Enhance bad response exception CS.

Enhance bad response exception CS.


<?php

namespace RadDB\Providers;

use Laravel\Dusk\DuskServiceProvider;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        // Work around for MariaDB/MySQL "Specified key was too long" errors
        Schema::defaultStringLength(191);
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        if ($this->app->environment('local', 'testing')) {
            $this->app->register(DuskServiceProvider::class);
        }
    }
}

<?php

namespace RadDB\Providers;

use Laravel\Dusk\DuskServiceProvider;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        if ($this->app->environment('local', 'testing')) {
            $this->app->register(DuskServiceProvider::class);
        }
    }
}

Revert "Set default string length to work around key too long errors"

This reverts commit 70e0a7e8ba2c34e6d5ae097cf3d8a53217d87574.

Trying to undo some breakage


<?php
/**
 * UserFrosting (http://www.userfrosting.com)
 *
 * @link      https://github.com/userfrosting/UserFrosting
 * @license   https://github.com/userfrosting/UserFrosting/blob/master/licenses/UserFrosting.md (MIT License)
 */
namespace UserFrosting\Tests\Integration;

use UserFrosting\Tests\TestCase;

/**
 *    Tests for the Migrator Service
 *
 *    @author Louis Charette
 */
class DatabaseMigratorServiceTest extends TestCase
{
    public function testMigratorService()
    {
        $this->assertInstanceOf('UserFrosting\Sprinkle\Core\Database\Migrator\Migrator', $this->ci->migrator);
    }
}

<?php
/**
 * UserFrosting (http://www.userfrosting.com)
 *
 * @link      https://github.com/userfrosting/UserFrosting
 * @license   https://github.com/userfrosting/UserFrosting/blob/master/licenses/UserFrosting.md (MIT License)
 */
namespace UserFrosting\Tests\Integration;

use UserFrosting\Sprinkle\Core\Tests\TestDatabase;
use UserFrosting\Tests\TestCase;

/**
 *    Tests for the Migrator Service
 *
 *    @author Louis Charette
 */
class DatabaseMigratorServiceTest extends TestCase
{
    use TestDatabase;

    /**
     * @inheritDoc
     */
    public function setUp()
    {
        parent::setUp();

        // Setup test database
        $this->setupTestDatabase();
    }

    public function testMigratorService()
    {
        $this->assertInstanceOf('UserFrosting\Sprinkle\Core\Database\Migrator\Migrator', $this->ci->migrator);
    }
}

Fix issue with test when no database is defined


<?php

namespace Concrete\Core\Application\UserInterface\Sitemap;

use Concrete\Core\Application\UserInterface\Sitemap\TreeCollection\TreeCollectionJsonFormatter;
use JsonSerializable;

final class JsonFormatter implements JsonSerializable
{
    /**
     * @var \Concrete\Core\Application\UserInterface\Sitemap\ProviderInterface
     */
    protected $provider;

    /**
     * @param \Concrete\Core\Application\UserInterface\Sitemap\ProviderInterface $provider
     */
    public function __construct(ProviderInterface $provider)
    {
        $this->provider = $provider;
    }

    /**
     * {@inheritdoc}
     *
     * @see JsonSerializable::jsonSerialize()
     */
    public function jsonSerialize()
    {
        $data = [];

        if ($this->provider->includeMenuInResponse()) {
            $collection = $this->provider->getTreeCollection($this->provider->getRequestedSiteTree());
            $formatter = new TreeCollectionJsonFormatter($collection);
            $data['trees'] = $formatter;
            $data['children'] = $this->provider->getRequestedNodes();
        } else {
            return $this->provider->getRequestedNodes();
        }

        return $data;
    }
}

<?php

namespace Concrete\Core\Application\UserInterface\Sitemap;

use Concrete\Core\Application\UserInterface\Sitemap\TreeCollection\TreeCollectionJsonFormatter;
use JsonSerializable;

final class JsonFormatter implements JsonSerializable
{
    /**
     * @var \Concrete\Core\Application\UserInterface\Sitemap\ProviderInterface
     */
    protected $provider;

    /**
     * @param \Concrete\Core\Application\UserInterface\Sitemap\ProviderInterface $provider
     */
    public function __construct(ProviderInterface $provider)
    {
        $this->provider = $provider;
    }

    /**
     * {@inheritdoc}
     *
     * @see JsonSerializable::jsonSerialize()
     */
    public function jsonSerialize()
    {
        $data = [];

        if ($this->provider->includeMenuInResponse()) {
            $collection = $this->provider->getTreeCollection($this->provider->getRequestedSiteTree());
            $formatter = new TreeCollectionJsonFormatter($collection);
            $data['trees'] = $formatter;
            $data['children'] = $this->provider->getRequestedNodes();
            $siteTree = $this->provider->getRequestedSiteTree();
            $data['homeCID'] = $siteTree === null ? null : ((int) $siteTree->getSiteHomePageID() ?: null);
        } else {
            return $this->provider->getRequestedNodes();
        }

        return $data;
    }
}

Send the home CID for the sitemap to the client


<?php
/**
  * @package Module
  * @subpackage About
  */

/**
  * @package Module
  * @subpackage About
  */
class AboutWebModule extends WebModule {
  protected $id = 'about';

  private function getPhraseForDevice() {
    switch($this->platform) {
      case 'iphone':
        return 'iPhone';

      case 'android':
        return 'Android phones';

      default:
        switch ($this->pagetype) {
          case 'compliant':
            return 'touchscreen phones';

          case 'basic':
          default:
            return 'non-touchscreen phones';
        }
    }
  }

  protected function initializeForPage() {
    switch ($this->page) {
      case 'index':
        $this->loadPageConfigFile('index', 'aboutPages');
        break;

      case 'about_site':
        $this->assign('devicePhrase', $this->getPhraseForDevice()); // TODO: this should be more generic, not part of this module
        break;

      case 'help':
      case 'credits':
      case 'about':
      case 'pane':
        break;

      default:
        $this->redirectTo('index');
        break;
    }
  }
}

<?php
/**
  * @package Module
  * @subpackage About
  */

/**
  * @package Module
  * @subpackage About
  */
class AboutWebModule extends WebModule {
  protected $id = 'about';

  private function getPhraseForDevice() {
    switch($this->platform) {
      case 'iphone':
        return $this->pagetype == 'tablet' ? 'iPad' : 'iPhone';

      case 'android':
        return 'Android '.($this->pagetype == 'tablet' ? 'tablets' : 'phones');

      default:
        switch ($this->pagetype) {
          case 'tablet':
            return 'tablet computers';

          case 'compliant':
            return 'touchscreen phones';

          case 'basic':
          default:
            return 'non-touchscreen phones';
        }
    }
  }

  protected function initializeForPage() {
    switch ($this->page) {
      case 'index':
        $this->loadPageConfigFile('index', 'aboutPages');
        break;

      case 'about_site':
        $this->assign('devicePhrase', $this->getPhraseForDevice()); // TODO: this should be more generic, not part of this module
        break;

      case 'help':
      case 'credits':
      case 'about':
      case 'pane':
        break;

      default:
        $this->redirectTo('index');
        break;
    }
  }
}

Add device descriptions for tablets

Add device descriptions for tablets


<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class HomeController extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('googleAPIProxy');
    }

    public function index()
    {
        $data = [
            'search' => false
        ];
        $this->load->view('templates/header');
        $this->load->view('index', $data);
        $this->load->view('templates/footer');
    }

    public function search()
    {
        $this->load->driver('cache');

        $cityName = str_replace(' ', '+', $this->input->post('place_name'));
        $cityNameAPIKey = sprintf('GoogleAPI-%s', $cityName);

        $result = $this->cache->file->get($cityNameAPIKey);

        if (!$result) {
            $result = $this->googleAPIProxy->getSearchPlaceResult($cityName);
            $this->cache->file->save($cityNameAPIKey, $result, CACHE_TIME);
        }

        $data = [
            'search' => true,
            'cityName' => $cityName,
            'searchResult' =>  json_decode($result),
        ];

        $this->load->view('templates/header');
        $this->load->view('index', $data);
        $this->load->view('templates/footer');
    }
}

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class HomeController extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->library('googleAPIProxy');
    }

    public function index()
    {
        $data = [
            'search' => false
        ];
        $this->load->view('templates/header');
        $this->load->view('index', $data);
        $this->load->view('templates/footer');
    }

    public function search()
    {
        $this->load->driver('cache');

        $cityName = str_replace(' ', '+', $this->input->post('city_name'));
        $cityNameAPIKey = sprintf('GoogleAPI-%s', $cityName);

        $result = $this->cache->file->get($cityNameAPIKey);

        if (!$result) {
            $result = $this->googleAPIProxy->getSearchPlaceResult($cityName);
            $this->cache->file->save($cityNameAPIKey, $result, CACHE_TIME);
        }

        $data = [
            'search' => true,
            'cityName' => $cityName,
            'searchResult' =>  json_decode($result),
        ];

        $this->load->view('templates/header');
        $this->load->view('index', $data);
        $this->load->view('templates/footer');
    }
}

Rename variable from placeName to cityName


<?php

/*
 * This file is part of the JsonSchema package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace JsonSchema\Constraints;

/**
 * The Enum Constraints, validates an element against a given set of possibilities
 *
 * @author Robert Schönthal <seroscho@googlemail.com>
 * @author Bruno Prieto Reis <bruno.p.reis@gmail.com>
 */
class Enum extends Constraint
{
    /**
     * {@inheritDoc}
     */
    public function check($element, $schema = null, $path = null, $i = null)
    {
        // Only validate enum if the attribute exists
        if ($element instanceof Undefined && (!isset($schema->required) || !$schema->required))  {
            return;
        }

        foreach ($schema->enum as $enum) {
            if ((gettype($element) === gettype($enum)) && ($element == $enum)) {
                return;
            }
        }

        $this->addError($path, "does not have a value in the enumeration " . print_r($schema->enum, true));
    }
}

<?php

/*
 * This file is part of the JsonSchema package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace JsonSchema\Constraints;

/**
 * The Enum Constraints, validates an element against a given set of possibilities
 *
 * @author Robert Schönthal <seroscho@googlemail.com>
 * @author Bruno Prieto Reis <bruno.p.reis@gmail.com>
 */
class Enum extends Constraint
{
    /**
     * {@inheritDoc}
     */
    public function check($element, $schema = null, $path = null, $i = null)
    {
        // Only validate enum if the attribute exists
        if ($element instanceof Undefined && (!isset($schema->required) || !$schema->required))  {
            return;
        }

        foreach ($schema->enum as $enum) {
            if ((gettype($element) === gettype($enum)) && ($element === $enum)) {
                return;
            }
        }

        $this->addError($path, "does not have a value in the enumeration " . print_r($schema->enum, true));
    }
}

Make the enum element comparison strict

Make the enum element comparison strict

The current check is matching numeric strings that are not equal ( like "604.1" == "604.10" because of PHP's == behavior that converts numeric strings to numbers and then performs a numeric comparison), even if type is checked before the comparison, the value should be identic


<?php echo $recipe->name; ?>

Servings

        <?php echo $recipe->servings; ?>

Prep Time

        <?php echo display_time($recipe->time_prep); ?>

Cook Time

        <?php echo display_time($recipe->time_cook); ?>

Ingredients

    <?php
    foreach ($ingredients as $single_ingredient) {
        $data = array(
            'ingredient' => $single_ingredient
    );
    $this->load->view('recipes/_ingredient', $data);
    }
    ?>

Steps

    <?php
    foreach ($steps as $single_step) {
        $data = array(
            'step' => $single_step
        );
        $this->load->view('recipes/_step', $data);
    }
    ?>

<?php echo $recipe->name; ?>

Servings

        <?php echo $recipe->servings; ?>

Prep Time

        <?php echo display_time($recipe->time_prep); ?>

Cook Time

        <?php echo display_time($recipe->time_cook); ?>

Ingredients

    <?php
    foreach ($ingredients as $single_ingredient) {
        $data = array(
            'ingredient' => $single_ingredient
    );
    $this->load->view('recipes/_ingredient', $data);
    }
    ?>

    <?php $this->load->view('recipes/_add_ingredient'); ?>

Steps

    <?php
    foreach ($steps as $single_step) {
        $data = array(
            'step' => $single_step
        );
        $this->load->view('recipes/_step', $data);
    }
    ?>

Add button appears but not aligned

Add button appears but not aligned


<?php
App::uses('AppModel', 'Model');

/**
 * Product Listing Model
 */
class ProductListing extends AppModel
{
	public $hasAndBelongsToMany = array(
		'Buyer' => array(
			'className' => 'Person',
			'joinTable' => 'product_listing_buyers',
			'associationForeignKey' => 'person_id',
			'unique' => true
		)
	);

	public $hasMany = array(
		'Comment' => array(
			'className' => 'ProductListingComment',
			'foreignKey' => 'product_listing_id',
			'dependent' => true
		)
	);

	public function isOwnedBy($listingId, $personId)
	{
		$listing = $this->findById($listingId);
		return (string)$listing['ProductListing']['creator_id'] === (string)$personId;
	}
}

<?php
App::uses('AppModel', 'Model');

/**
 * Product Listing Model
 */
class ProductListing extends AppModel
{
	public $hasAndBelongsToMany = array(
		'Buyer' => array(
			'className' => 'Person',
			'joinTable' => 'product_listing_buyers',
			'associationForeignKey' => 'person_id',
			'unique' => true
		)
	);

	public $hasMany = array(
		'Comment' => array(
			'className' => 'ProductListingComment',
			'foreignKey' => 'product_listing_id',
			'dependent' => true
		)
	);

	/**
	 * Checks if the given listing is owned by the person specified.
	 *
	 * @param int $listingId
	 * @param string  $personId
	 * @return boolean
	 */
	public function isOwnedBy($listingId, $personId)
	{
		$listing = $this->findById($listingId);
		return (string)$listing['ProductListing']['creator_id'] === (string)$personId;
	}

	/**
	 * Checks if a listing is only visible by friends.
	 *
	 * @param int $listingId
	 * @return boolean
	 */
	public function isFriendsOnly($listingId)
	{
		$listing = $this->findById($listingId);
		return intval($listing['ProductListing']['friends_only']) !== 0;
	}
}

Implement isFriendsOnly to check for friends-only listings.


<?php
// ~/Sites/presentation/mvc-basics/resources/views/event/tickets/index.blade.php
// Using your text editor, edit the `index.blade.php` file and replace the placeholder
// cell with a link to edit the ticket.

    {{ $ticket->id }}
    {{ $ticket->ticketholder_name }}
    {{ $ticket->ticket_price }}

         $ticket->id]) }}">Edit

Update laravel/mvc-basics/step-by-step/36 with theme formatting


<?php
/**
 * Class Google\Site_Kit\Core\Authentication\User_Input_State
 *
 * @package   Google\Site_Kit
 * @copyright 2020 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

namespace Google\Site_Kit\Core\Authentication;

use Google\Site_Kit\Core\Storage\User_Setting;

/**
 * Class representing user_input_state for the user.
 *
 * @since 1.20.0
 * @access private
 * @ignore
 */
final class User_Input_State extends User_Setting {

	/**
	 * User option key.
	 */
	const OPTION = 'googlesitekit_user_input_state';

	/**
	 * Value required key.
	 */
	const VALUE_REQUIRED = 'required';

	/**
	 * Value completed key.
	 */
	const VALUE_COMPLETED = 'completed';

	/**
	 * Value missing key.
	 */
	const VALUE_MISSING = 'missing';

	/**
	 * Gets the callback for sanitizing the setting's value before saving.
	 *
	 * @since n.e.x.t
	 *
	 * @return callable|null
	 */
	protected function get_sanitize_callback() {
		return function( $value ) {
			if ( ! in_array( $value, array( self::VALUE_COMPLETED, self::VALUE_MISSING, self::VALUE_REQUIRED, '' ), true ) ) {
				return false;
			}

			return $value;
		};
	}
}

<?php
/**
 * Class Google\Site_Kit\Core\Authentication\User_Input_State
 *
 * @package   Google\Site_Kit
 * @copyright 2020 Google LLC
 * @license   https://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0
 * @link      https://sitekit.withgoogle.com
 */

namespace Google\Site_Kit\Core\Authentication;

use Google\Site_Kit\Core\Storage\User_Setting;

/**
 * Class representing user_input_state for the user.
 *
 * @since 1.20.0
 * @access private
 * @ignore
 */
final class User_Input_State extends User_Setting {

	/**
	 * User option key.
	 */
	const OPTION = 'googlesitekit_user_input_state';

	/**
	 * Value required key.
	 */
	const VALUE_REQUIRED = 'required';

	/**
	 * Value completed key.
	 */
	const VALUE_COMPLETED = 'completed';

	/**
	 * Value missing key.
	 */
	const VALUE_MISSING = 'missing';

	/**
	 * Gets the callback for sanitizing the setting's value before saving.
	 *
	 * @since n.e.x.t
	 *
	 * @return callable|null
	 */
	protected function get_sanitize_callback() {
		return function( $value ) {
			if ( ! in_array( $value, array( self::VALUE_COMPLETED, self::VALUE_MISSING, self::VALUE_REQUIRED, '' ), true ) ) {
				return false;
			}

			return true;
		};
	}
}

Return true if everything is ok.

Return true if everything is ok.


<?php

namespace Listabierta\Bundle\MunicipalesBundle\Form\Type;

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

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

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    }

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

<?php

namespace Listabierta\Bundle\MunicipalesBundle\Form\Type;

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

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

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    	$resolver->setDefaults(
    			array(
    					'allow_extra_fields' => TRUE
    			)
    	);
    }

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

Allow extra fields in step 6 voters

Allow extra fields in step 6 voters


<?php

require_once __DIR__ . "/wavepipe.php";

// Attempt a login request using test credentials
$login = json_decode(file_get_contents("http://localhost:8080/api/v0/login?u=test&p=test"), true);
if (empty($login)) {
	printf("Failed to decode login JSON");
	exit(1);
}

// Store necessary login information
$publicKey = $login["session"]["publicKey"];
$secretKey = $login["session"]["secretKey"];

// Iterate and test all JSON APIs
$apiCalls = array(
	"/api/v0/albums",
	"/api/v0/artists",
	"/api/v0/songs",
	"/api/v0/logout",
);

foreach ($apiCalls as $a) {
	// Create a nonce
	$nonce = generateNonce();

	// Create the necessary API signature
	$signature = apiSignature($publicKey, $nonce, "GET", $a, $secretKey);

	// Generate URL
	$url = sprintf("http://localhost:8080%s?s=%s:%s:%s", $a, $publicKey, $nonce, $signature);

	// Perform API call
	printf("%s: %s\n", $a, file_get_contents($url));
}

<?php

require_once __DIR__ . "/wavepipe.php";

// Attempt a login request using test credentials
$login = json_decode(file_get_contents("http://localhost:8080/api/v0/login?u=test&p=test"), true);
if (empty($login)) {
	printf("Failed to decode login JSON");
	exit(1);
}

// Store necessary login information
$publicKey = $login["session"]["publicKey"];
$secretKey = $login["session"]["secretKey"];

// Iterate and test all JSON APIs
$apiCalls = array(
	"/api/v0/albums",
	"/api/v0/albums/1",
	"/api/v0/artists",
	"/api/v0/artists/1",
	"/api/v0/folders",
	"/api/v0/folders/1",
	"/api/v0/songs",
	"/api/v0/songs/1",
	"/api/v0/logout",
);

foreach ($apiCalls as $a) {
	// Create a nonce
	$nonce = generateNonce();

	// Create the necessary API signature
	$signature = apiSignature($publicKey, $nonce, "GET", $a, $secretKey);

	// Generate URL
	$url = sprintf("http://localhost:8080%s?s=%s:%s:%s", $a, $publicKey, $nonce, $signature);

	// Perform API call
	printf("%s: %s\n", $a, file_get_contents($url));
}

Add more API calls to tests

Add more API calls to tests


<?php

/*
 * This file is part of the Zephir.
 *
 * (c) Zephir Team <team@zephir-lang.com>
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Zephir;

/**
 * Zephir\Zephir.
 */
final class Zephir
{
    const VERSION = '0.12.2-$Id$';

    const RELEASE_DATE = '$release-date$';

    const LOGO = <<<'ASCII'
 _____              __    _
/__  /  ___  ____  / /_  (_)____
  / /  / _ \/ __ \/ __ \/ / ___/
 / /__/  __/ /_/ / / / / / /
/____/\___/ .___/_/ /_/_/_/
         /_/

ASCII;
}

<?php

/*
 * This file is part of the Zephir.
 *
 * (c) Zephir Team <team@zephir-lang.com>
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Zephir;

/**
 * Zephir\Zephir.
 */
final class Zephir
{
    const VERSION = '0.12.2-$Id$';

    const LOGO = <<<'ASCII'
 _____              __    _
/__  /  ___  ____  / /_  (_)____
  / /  / _ \/ __ \/ __ \/ / ___/
 / /__/  __/ /_/ / / / / / /
/____/\___/ .___/_/ /_/_/_/
         /_/

ASCII;
}

Remove no longer used constant

Remove no longer used constant


<?php namespace Krucas\Counter\Integration\Laravel;

use Illuminate\Support\ServiceProvider;
use Krucas\Counter\Counter;

class CounterServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap service provider.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes(array(
            __DIR__ . '/../../../../config/counter.php' => config_path('counter.php'),
        ), 'config');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(__DIR__ . '/../../../../config/counter.php', 'counter');

        $this->app->singleton('Krucas\Counter\Integration\Laravel\DatabaseRepository', function ($app) {
            return new DatabaseRepository($app['db'], $app['config']->get('counter.table'));
        });

        $this->app->singleton('counter', function ($app) {
            $repositoryClass = $app['config']->get('counter.repository');

            return new Counter($app->make($repositoryClass));
        });

        $this->app->alias('counter', 'Krucas\Counter\Counter');
    }
}

<?php namespace Krucas\Counter\Integration\Laravel;

use Illuminate\Support\ServiceProvider;
use Krucas\Counter\Counter;

class CounterServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap service provider.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes(array(
            __DIR__ . '/../../../../config/counter.php' => config_path('counter.php'),
        ), 'config');
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->mergeConfigFrom(__DIR__ . '/../../../../config/counter.php', 'counter');

        $this->app->singleton('Krucas\Counter\Integration\Laravel\DatabaseRepository', function ($app) {
            return new DatabaseRepository($app['db']->connection(), $app['config']->get('counter.table'));
        });

        $this->app->singleton('counter', function ($app) {
            $repositoryClass = $app['config']->get('counter.repository');

            return new Counter($app->make($repositoryClass));
        });

        $this->app->alias('counter', 'Krucas\Counter\Counter');
    }
}

Use default connection for DB repository


<?php

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

namespace Symfony\Bundle\WebProfilerBundle\Tests\Resources;

use PHPUnit\Framework\TestCase;

class IconTest extends TestCase
{
    /**
     * @dataProvider provideIconFilePaths
     */
    public function testIconFileContents($iconFilePath)
    {
        $this->assertMatchesRegularExpression('~<svg xmlns="http://www.w3.org/2000/svg" width="\d+" height="\d+" viewBox="0 0 \d+ \d+">.*</svg>~s', file_get_contents($iconFilePath), sprintf('The SVG metadata of the %s icon is different than expected (use the same as the other icons).', $iconFilePath));
    }

    public function provideIconFilePaths()
    {
        return array_map(function ($filePath) { return (array) $filePath; }, glob(__DIR__.'/../../Resources/views/Icon/*.svg'));
    }
}

<?php

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

namespace Symfony\Bundle\WebProfilerBundle\Tests\Resources;

use PHPUnit\Framework\TestCase;

class IconTest extends TestCase
{
    /**
     * @dataProvider provideIconFilePaths
     */
    public function testIconFileContents($iconFilePath)
    {
        $this->assertMatchesRegularExpression('~<svg xmlns="http://www.w3.org/2000/svg" width="\d+" height="\d+" viewBox="0 0 \d+ \d+"[^>]*+>.*</svg>~s', file_get_contents($iconFilePath), sprintf('The SVG metadata of the %s icon is different than expected (use the same as the other icons).', $iconFilePath));
    }

    public function provideIconFilePaths()
    {
        return array_map(function ($filePath) { return (array) $filePath; }, glob(__DIR__.'/../../Resources/views/Icon/*.svg'));
    }
}

Fix tests about web profiler icons

[WebProfilerBundle] Fix tests about web profiler icons


<?php
namespace Craft;

class FieldManagerPlugin extends BasePlugin
{
    // =========================================================================
    // PLUGIN INFO
    // =========================================================================

    public function getName()
    {
        return Craft::t('Field Manager');
    }

    public function getVersion()
    {
        return '1.5.5';
    }

    public function getSchemaVersion()
    {
        return '1.0.0';
    }

    public function getDeveloper()
    {
        return 'Verbb';
    }

    public function getDeveloperUrl()
    {
        return 'https://verbb.io';
    }

    public function getPluginUrl()
    {
        return 'https://github.com/verbb/field-manager';
    }

    public function getDocumentationUrl()
    {
        return $this->getPluginUrl() . '/blob/master/README.md';
    }

    public function getReleaseFeedUrl()
    {
        return 'https://raw.githubusercontent.com/verbb/field-manager/master/changelog.json';
    }

    public function hasCpSection()
    {
        return craft()->fieldManager->isCpSectionEnabled() ? true : false;
    }

    public function getSettingsHtml()
    {
        return craft()->templates->render('fieldmanager/settings', array(
            'settings' => $this->getSettings(),
        ));
    }

    protected function defineSettings()
    {
        return array(
            'cpSectionEnabled' => array( AttributeType::Bool, 'default' => true ),
        );
    }
}

<?php
namespace Craft;

class FieldManagerPlugin extends BasePlugin
{
    // =========================================================================
    // PLUGIN INFO
    // =========================================================================

    public function getName()
    {
        return Craft::t('Field Manager');
    }

    public function getVersion()
    {
        return '1.5.5';
    }

    public function getSchemaVersion()
    {
        return '1.0.0';
    }

    public function getDeveloper()
    {
        return 'Verbb';
    }

    public function getDeveloperUrl()
    {
        return 'https://verbb.io';
    }

    public function getPluginUrl()
    {
        return 'https://github.com/verbb/field-manager';
    }

    public function getDocumentationUrl()
    {
        return 'https://verbb.io/craft-plugins/field-manager/docs';
    }

    public function getReleaseFeedUrl()
    {
        return 'https://raw.githubusercontent.com/verbb/field-manager/craft-2/changelog.json';
    }

    public function hasCpSection()
    {
        return craft()->fieldManager->isCpSectionEnabled() ? true : false;
    }

    public function getSettingsHtml()
    {
        return craft()->templates->render('fieldmanager/settings', array(
            'settings' => $this->getSettings(),
        ));
    }

    protected function defineSettings()
    {
        return array(
            'cpSectionEnabled' => array( AttributeType::Bool, 'default' => true ),
        );
    }
}

Update Documentation URL and Release Feed


Fix issue with incorrect URL in Google Analytics script.

Better research later! Why does it work with my other sites, but not for this one?


<?php
/**
 * This file is part of laravel-stubs package.
 *
 * @author ATehnix <atehnix@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace ATehnix\LaravelStubs\Console;

use Illuminate\Foundation\Console\ConsoleMakeCommand as BaseConsoleMakeCommand;

class ConsoleMakeCommand extends BaseConsoleMakeCommand
{
    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        $stub = config('stubs.path').'/console.stub';

        return file_exists($stub) ? $stub : parent::getStub();
    }

    /**
     * Get the default namespace for the class.
     *
     * @param  string  $rootNamespace
     * @return string
     */
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace.config('stubs.namespaces.console');
    }
}

<?php
/**
 * This file is part of laravel-stubs package.
 *
 * @author ATehnix <atehnix@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ATehnix\LaravelStubs\Console;

use Illuminate\Foundation\Console\ConsoleMakeCommand as BaseConsoleMakeCommand;

class ConsoleMakeCommand extends BaseConsoleMakeCommand
{
    /**
     * Get the stub file for the generator.
     *
     * @return string
     */
    protected function getStub()
    {
        $stub = config('stubs.path') . '/console.stub';

        return file_exists($stub) ? $stub : parent::getStub();
    }

    /**
     * Get the default namespace for the class.
     *
     * @param  string $rootNamespace
     * @return string
     */
    protected function getDefaultNamespace($rootNamespace)
    {
        return $rootNamespace . config('stubs.namespaces.command');
    }
}

Change key for console namespace

Change key for console namespace


<?php
/*
 * (c) webfactory GmbH <info@webfactory.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Webfactory\ContentMapping\SourceAdapter\Propel;

use Psr\Log\LoggerInterface;

/**
 * Automagically implementation of the adapter for Propel as a source system.
 *
 * @final by default
 */
final class GenericPropelSourceAdapter extends PropelSourceAdapter
{
    /**
     * @var string Name of the class of the objects provided by this source.
     */
    protected $className;

    /**
     * @var string Name of the method to call on the peer to get the objects ordered by their id.
     */
    protected $resultSetMethod;

    /**
     * @param string $className Name of the class of the objects provided by this source.
     * @param string $resultSetMethod Name of the method to call on the peer to get the objects ordered by their id.
     * @param LoggerInterface|null $logger
     */
    public function __construct($className, $resultSetMethod = 'doSelectRS', LoggerInterface $logger = null)
    {
        $this->className = $className;
        $this->resultSetMethod = $resultSetMethod;
        $this->logger = $this->setLogger($logger);
    }

    /**
     * @return mixed|null
     */
    protected function createPeer()
    {
        $cls = \Classloader::load("{$this->className}Peer");
        return new $cls();
    }

    /**
     * {@inheritDoc}
     */
    protected function createResultSet($peer, \Criteria $criteria)
    {
        return $peer->{$this->resultSetMethod}($criteria);
    }
}

<?php
/*
 * (c) webfactory GmbH <info@webfactory.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Webfactory\ContentMapping\SourceAdapter\Propel;

use Psr\Log\LoggerInterface;

/**
 * Automagically implementation of the adapter for Propel as a source system.
 *
 * @final by default
 */
final class GenericPropelSourceAdapter extends PropelSourceAdapter
{
    /**
     * @var string Name of the class of the objects provided by this source.
     */
    protected $className;

    /**
     * @var string Name of the method to call on the peer to get the objects ordered by their id.
     */
    protected $resultSetMethod;

    /**
     * @param string $className Name of the class of the objects provided by this source.
     * @param string $resultSetMethod Name of the method to call on the peer to get the objects ordered by their id.
     * @param LoggerInterface|null $logger
     */
    public function __construct($className, $resultSetMethod = 'doSelectRS', LoggerInterface $logger = null)
    {
        $this->className = $className;
        $this->resultSetMethod = $resultSetMethod;
        $this->setLogger($logger);
    }

    /**
     * @return mixed|null
     */
    protected function createPeer()
    {
        $cls = \Classloader::load("{$this->className}Peer");
        return new $cls();
    }

    /**
     * {@inheritDoc}
     */
    protected function createResultSet($peer, \Criteria $criteria)
    {
        return $peer->{$this->resultSetMethod}($criteria);
    }
}

Fix that the logger was lost

Fix that the logger was lost


<?php

namespace Spark\Core;

use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\ProcessBuilder;

class DevelopmentServer
{
    protected $documentRoot;
    protected $router;

    function __construct($documentRoot, $router)
    {
        $this->documentRoot = $documentRoot;
        $this->router = $router;
    }

    function run($serverName = null, $port = null)
    {
        $serverName = $serverName ?: "localhost";
        $port = $port ?: 3000;

        $builder = new ProcessBuilder();
        $builder->add((new PhpExecutableFinder)->find());

        # Start PHP in development server mode
        $builder->add('-S');
        $builder->add("$serverName:$port");

        # Add the document root
        $builder->add('-t');
        $builder->add($this->documentRoot);

        # Add the router script
        $builder->add($this->router);

        $process = $builder->getProcess();
        $process->setTimeout(null);

        printf("Running development server on %s:%d ..." . PHP_EOL, $serverName, $port);

        $process->run(function($type, $err) {
            fwrite(STDERR, "$err\n");
        });
    }
}

<?php

namespace Spark\Core;

use Symfony\Component\Process\PhpExecutableFinder;
use Symfony\Component\Process\ProcessBuilder;

class DevelopmentServer
{
    protected $documentRoot;
    protected $router;

    function __construct($documentRoot, $router)
    {
        $this->documentRoot = $documentRoot;
        $this->router = $router;
    }

    function run($serverName = null, $port = null)
    {
        $serverName = $serverName ?: "localhost";
        $port = $port ?: 3000;

        $builder = new ProcessBuilder();
        $builder->add((new PhpExecutableFinder)->find());

        # Start PHP in development server mode
        $builder->add('-S');
        $builder->add("$serverName:$port");

        # Add the document root
        $builder->add('-t');
        $builder->add($this->documentRoot);

        # Add the router script
        $builder->add($this->router);

        $process = $builder->getProcess();
        $process->setTimeout(null);

        printf("Running development server on %s:%d ..." . PHP_EOL, $serverName, $port);
        printf("Stop by pressing [CTRL] + [c]\n");

        $process->run(function($type, $err) {
            fwrite(STDERR, "$err\n");
        });
    }
}

Add instruction for stopping dev server

Add instruction for stopping dev server


@title('Manage API keys: '.$user->name)
@extends('app')

@section('content')

Manage API keys: {{ $user->name }}

id) }}">Control Panel

Manage API keys

Active API Keys

            Key
            Generated

        @foreach ($user->api_keys as $key)

                    {{ $key->key }}

                    Context: {{ $key->app }}

                    @date($key->created_at)

                    from {{ $key->ip }}

                    @form(panel/delete-key)
                        @hidden(id $key)
                        <button class="btn btn-danger btn-xs" type="submit">

                            Delete
                        </button>
                    @endform

        @endforeach

Generate a new API key

    @form(panel/add-key)
        @hidden(id $user)
        @text(app) = Context (what the key will be used for)
        @submit = Create Key
    @endform
@endsection

@title('Manage API keys: '.$user->name)
@extends('app')

@section('content')

Manage API keys: {{ $user->name }}

id) }}">Control Panel

Manage API keys

        See this page for how to use the API.

Active API Keys

            Key
            Generated

        @foreach ($user->api_keys as $key)

                    {{ $key->key }}

                    Context: {{ $key->app }}

                    @date($key->created_at)

                    from {{ $key->ip }}

                    @form(panel/delete-key)
                        @hidden(id $key)
                        <button class="btn btn-danger btn-xs" type="submit">

                            Delete
                        </button>
                    @endform

        @endforeach

Generate a new API key

    @form(panel/add-key)
        @hidden(id $user)
        @text(app) = Context (what the key will be used for)
        @submit = Create Key
    @endform
@endsection

Add API doc link to key management page

Add API doc link to key management page


<?php

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

namespace Symfony\Bundle\SecurityBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Compiler\AddAuthenticationProvidersPass;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Compiler\AddSecurityVotersPass;

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

        $container->addCompilerPass(new AddSecurityVotersPass());
        $container->addCompilerPass(new AddAuthenticationProvidersPass());
    }

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

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

<?php

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

namespace Symfony\Bundle\SecurityBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Compiler\AddAuthenticationProvidersPass;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Compiler\AddSecurityVotersPass;

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

        $container->addCompilerPass(new AddSecurityVotersPass());
        $container->addCompilerPass(new AddAuthenticationProvidersPass());
    }

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

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

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


<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$db_name = "grade4_db";
$table_name = "students";
$name = $_POST['studname'];
$passphrase = $_POST['password'];
$url_success = 'pages/main_menu.php';
$url_fail = 'index.php';

try {
    $conn = new PDO("mysql:host=$servername;dbname=$db_name", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT id, name, password FROM $table_name WHERE name = '$name'");
    $stmt->execute();

    if ($stmt->rowCount() > 0) {
    	# code...
    	echo $name . ' exists';
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($result['password'] == $passphrase) {
            $_SESSION['id'] = $result['id'];
            $_SESSION['name'] = $name;
            $_SESSION['notification'] = null;
            header("Location: $url_success");
        } else {
            $_SESSION['notification'] = 'The password you used was wrong.';
            $_SESSION['notificationType'] = 'fail';
            header("Location: $url_fail");
        }
    }
    echo "Connected successfully";
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }
?>

<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$db_name = "grade4_db";
$table_name = "students";
$name = $_POST['studname'];
$passphrase = $_POST['password'];
$url_success = 'pages/main_menu.php';
$url_fail = 'index.php';

try {
    $conn = new PDO("mysql:host=$servername;dbname=$db_name", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT id, name, password FROM $table_name WHERE name = '$name'");
    $stmt->execute();

    if ($stmt->rowCount() > 0) {
    	# code...
    	echo $name . ' exists';
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($result['password'] == $passphrase) {
            $_SESSION['id'] = $result['id'];
            $_SESSION['name'] = $name;
            $_SESSION['notification'] = null;
            $_SESSION['notificationType'] = null;
            header("Location: $url_success");
        } else {
            $_SESSION['notification'] = 'The password you used was wrong.';
            $_SESSION['notificationType'] = 'fail';
            header("Location: $url_fail");
        }
    }
    echo "Connected successfully";
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }
?>

Remove notification type on log in

Remove notification type on log in


<?php
/**
 * Linkedin API for Laravel Framework
 *
 * @author    Mauri de Souza Nunes <mauri870@gmail.com>
 * @license   https://opensource.org/licenses/MIT MIT License
 */

namespace Artesaos\LinkedIn;

use Illuminate\Support\ServiceProvider;

class LinkedinServiceProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        //Publish config file
        if(function_exists('config_path')){
            //If is not a Lumen App...
            $this->publishes([
                __DIR__ . '/config/linkedin.php' => config_path('linkedin.php'),
            ]);

            $this->mergeConfigFrom(
                __DIR__ . '/config/linkedin.php','linkedin'
            );
        }
    }

    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        //Bind the facade and pass api construct parameters
        $this->app->bind('LinkedIn', function(){
            $api_key = config('linkedin.api_key');
            $api_secret = config('linkedin.api_secret');

            return new LinkedInLaravel($api_key, $api_secret);
        });
    }
}

<?php
/**
 * Linkedin API for Laravel Framework
 *
 * @author    Mauri de Souza Nunes <mauri870@gmail.com>
 * @license   https://opensource.org/licenses/MIT MIT License
 */

namespace Artesaos\LinkedIn;

use Illuminate\Support\ServiceProvider;
use Http\Adapter\Guzzle6\Client as HttpClient;
use Http\Message\MessageFactory\GuzzleMessageFactory as HttpGuzzleMessageFactory;

class LinkedinServiceProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        //Publish config file
        if(function_exists('config_path')){
            //If is not a Lumen App...
            $this->publishes([
                __DIR__ . '/config/linkedin.php' => config_path('linkedin.php'),
            ]);

            $this->mergeConfigFrom(
                __DIR__ . '/config/linkedin.php','linkedin'
            );
        }
    }

    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        //Bind the facade and pass api construct parameters
        $this->app->bind('LinkedIn', function(){
            $api_key = config('linkedin.api_key');
            $api_secret = config('linkedin.api_secret');

            $linkedIn = new LinkedInLaravel($api_key, $api_secret);
            $linkedIn->setHttpClient(new HttpClient());
            $linkedIn->setHttpMessageFactory(new HttpGuzzleMessageFactory());

            return $linkedIn;
        });
    }
}

Set Guzzle 6 as Http Client And Http Message Factory.


<?php namespace Flarum\Core\Notifications;

use Flarum\Core\Users\User;

class NotificationRepository
{
    /**
     * Find a user's notifications.
     *
     * @param User $user
     * @param int|null $limit
     * @param int $offset
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function findByUser(User $user, $limit = null, $offset = 0)
    {
        $primaries = Notification::select(
            app('flarum.db')->raw('MAX(id) AS id'),
            app('flarum.db')->raw('SUM(is_read = 0) AS unread_count')
        )
            ->where('user_id', $user->id)
            ->whereIn('type', $user->getAlertableNotificationTypes())
            ->where('is_deleted', false)
            ->groupBy('type', 'subject_id')
            ->latest('time')
            ->skip($offset)
            ->take($limit);

        return Notification::with('subject')
            ->select('notifications.*', 'p.unread_count')
            ->mergeBindings($primaries->getQuery())
            ->join(app('flarum.db')->raw('('.$primaries->toSql().') p'), 'notifications.id', '=', 'p.id')
            ->latest('time')
            ->get();
    }
}

<?php namespace Flarum\Core\Notifications;

use Flarum\Core\Users\User;

class NotificationRepository
{
    /**
     * Find a user's notifications.
     *
     * @param User $user
     * @param int|null $limit
     * @param int $offset
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function findByUser(User $user, $limit = null, $offset = 0)
    {
        $primaries = Notification::select(
            app('flarum.db')->raw('MAX(id) AS id'),
            app('flarum.db')->raw('SUM(is_read = 0) AS unread_count')
        )
            ->where('user_id', $user->id)
            ->whereIn('type', $user->getAlertableNotificationTypes())
            ->where('is_deleted', false)
            ->groupBy('type', 'subject_id')
            ->orderByRaw('MAX(time) DESC')
            ->skip($offset)
            ->take($limit);

        return Notification::with('subject')
            ->select('notifications.*', 'p.unread_count')
            ->mergeBindings($primaries->getQuery())
            ->join(app('flarum.db')->raw('('.$primaries->toSql().') p'), 'notifications.id', '=', 'p.id')
            ->latest('time')
            ->get();
    }
}

Fix new notifications on old subjects not appearing


<?php

namespace FullyBaked\Pslackr\Messages;

class CustomMessage implements Message
{
    protected $text;

    protected $optionalFields = [];

    public function __construct($messageText)
    {
        $this->text = $messageText;
    }
    public function asJson()
    {
        $message = ['text' => 'This is a test message'];

        $message = array_merge($message, $this->optionalFields);

        return json_encode($message);
    }

    public function channel($channelName)
    {
        $this->optionalFields['channel'] = $channelName;
    }

    public function username($username)
    {
        $this->optionalFields['username'] = $username;
    }

    public function iconEmoji($token)
    {
        $this->optionalFields['icon_emoji'] = $token;
    }

    public function iconUrl($url)
    {
        $this->optionalFields['icon_url'] = $url;
    }
}

Add empty line between methods

Add empty line between methods


<?php
/**
 * @see       https://github.com/zendframework/zend-di for the canonical source repository
 * @copyright Copyright (c) 2018 Zend Technologies USA Inc. (https://www.zend.com)
 * @license   https://github.com/zendframework/zend-di/blob/master/LICENSE.md New BSD License
 */

namespace Zend\Di\Resolver;

use Psr\Container\ContainerInterface;

/**
 * Defines the injection to perform for a parameter
 */
interface InjectionInterface
{
    /**
     * @return mixed The resulting injection value
     */
    public function toValue(ContainerInterface $container);

    /**
     * @return string
     */
    public function export() : string;

    /**
     * @return bool
     */
    public function isExportable() : bool;
}

<?php
/**
 * @see       https://github.com/zendframework/zend-di for the canonical source repository
 * @copyright Copyright (c) 2018 Zend Technologies USA Inc. (https://www.zend.com)
 * @license   https://github.com/zendframework/zend-di/blob/master/LICENSE.md New BSD License
 */

namespace Zend\Di\Resolver;

use Psr\Container\ContainerInterface;

/**
 * Defines the injection to perform for a parameter
 */
interface InjectionInterface
{
    /**
     * @return mixed The resulting injection value
     */
    public function toValue(ContainerInterface $container);

    public function export() : string;

    public function isExportable() : bool;
}

Remove redundant return type in php doc

Remove redundant return type in php doc


<?php
namespace SD\Currency\DependencyInjection;

use SD\Currency\Repository;

trait CurrencyAwareTrait {
    private $autoDeclareCurrency = 'currency';
    private $currency;

    public function setCurrency(Repository $currency) {
        $this->currency = $currency;
    }
}

<?php
namespace SD\Currency\DependencyInjection;

use SD\Currency\Repository;

trait CurrencyAwareTrait {
    private $autoDeclareCurrency = 'currency';
    private $currency;

    public function setCurrency(Repository $currency) {
        $this->currency = $currency;
    }

    private function getCurrency(): Repository {
        return $this->currency;
    }
}

Add container getter to remove consumer dependency on variable name


<?php

namespace DigiTickets\VerifoneWebService\Message\NonSessionBased;

use DigiTickets\VerifoneWebService\Message\AbstractRemoteResponse;

class RefundResponse extends AbstractRemoteResponse
{
    /**
     * Return the error message
     *
     * @return string
     */
    public function getError()
    {
        // Get the transaction result and auth message.
        $txnResult = $this->data->getMsgDataAttribute('txnresult');
        $authmessage = $this->data->getMsgDataAttribute('authmessage');

        return $txnResult == 'APPROVED' ? null : $authmessage;
    }

    public function getTransactionId()
    {
        return $this->data->getMsgDataAttribute('transactionid');
    }
}

<?php

namespace DigiTickets\VerifoneWebService\Message\NonSessionBased;

use DigiTickets\VerifoneWebService\Message\AbstractRemoteResponse;
use DigiTickets\VerifoneWebService\Message\Objects\ProcessMsg\Message;

class RefundResponse extends AbstractRemoteResponse
{
    /**
     * Return the error message
     *
     * @return string
     */
    public function getError()
    {
        // Get the transaction result and auth message.
        $txnResult = $this->data->getMsgDataAttribute('txnresult');
        $authmessage = $this->data->getMsgDataAttribute('authmessage');

        return $txnResult == 'APPROVED' ? null : $authmessage;
    }

    public function getTransactionId()
    {
        return $this->data->getMsgDataAttribute('transactionid');
    }

    public function getCode()
    {
        // The authcode seems to be blank, but I'm including this for completeness.
        return $this->data->getMsgDataAttribute('authcode');
    }

    public function getMessage()
    {
        return $this->data->getMsgDataAttribute('txnresult');
    }

    public function getTransactionReference()
    {
        // Build a JSON-style collection of relevant values.
        /**
         * @var Message $responseData
         */
        $responseData = $this->data;
        return json_encode([
            'merchantreference' => $responseData->getMsgDataAttribute('merchantreference'),
            'transactionid' => $responseData->getMsgDataAttribute('transactionid'),
            'tid' => $responseData->getMsgDataAttribute('tid'),
            'schemename' => $responseData->getMsgDataAttribute('schemename'),
            'messagenumber' => $responseData->getMsgDataAttribute('messagenumber'),
            'pcavsresult' => $responseData->getMsgDataAttribute('pcavsresult'),
            'ad1avsresult' => $responseData->getMsgDataAttribute('ad1avsresult'),
            'cvcresult' => $responseData->getMsgDataAttribute('cvcresult'),
            'arc' => $responseData->getMsgDataAttribute('arc'),

        ]);
    }
}

Add various getters to the refund response to get data out.


<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

use Illuminate\Support\Facades\DB;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Purge all cached basecamp api calls';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        if(env('CACHE_DRIVER') != 'database'){
            return $this->error('Cache driver is not set to Database, no action was taken!');
        }

        if(false && $resp = $this->ask('Are you sure you want to purge cache? This will cause slowdowns until cache is rebuilt. (y/N)', 'n'))
            if(strtolower($resp)[0] == 'n')
                return null;

        $rows = DB::table('cache')->select('key')->where('key', 'like', config('cache.prefix').'api%')->delete();
        $this->info('Purged '.$rows.' items from the cache');
    }
}

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

use Illuminate\Support\Facades\DB;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Purge all cached basecamp api calls';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        if(env('CACHE_DRIVER') != 'database'){
            return $this->error('Cache driver is not set to Database, no action was taken!');
        }

        if($resp = $this->ask('Are you sure you want to purge cache? This will cause slowdowns until cache is rebuilt. (y/N)', 'n'))
            if(strtolower($resp)[0] == 'n')
                return null;

        $rows = DB::table('cache')->select('key')->where('key', 'like', config('cache.prefix').'api%')->delete();
        $this->info('Purged '.$rows.' items from the cache');
    }
}

Add safeguard for purging cache

Add safeguard for purging cache


<?php
exit;
/* connector for Turbellarian
estimated execution time: 18 hrs.
This connector gets data from website and rank information from a csv file.
*/

$timestart = microtime(1);

include_once(dirname(__FILE__) . "/../../config/environment.php");
require_library('connectors/TurbellarianAPI');
$GLOBALS['ENV_DEBUG'] = false;

$taxa = TurbellarianAPI::get_all_taxa();
$xml = SchemaDocument::get_taxon_xml($taxa);

$resource_path = CONTENT_RESOURCE_LOCAL_PATH . "185.xml";

$OUT = fopen($resource_path, "w+");
fwrite($OUT, $xml);
fclose($OUT);

$elapsed_time_sec = microtime(1)-$timestart;
echo "\n";
echo "elapsed time = $elapsed_time_sec sec              \n";
echo "elapsed time = " . $elapsed_time_sec/60 . " min   \n";
echo "elapsed time = " . $elapsed_time_sec/60/60 . " hr \n";
exit("\n\n Done processing.");

?>

<?php
exit;
/* connector for Turbellarian
estimated execution time: 18 hrs.
This connector gets data from website and rank information from a csv file.

as of       records
Oct 1 2010  17492
*/

$timestart = microtime(1);

include_once(dirname(__FILE__) . "/../../config/environment.php");
require_library('connectors/TurbellarianAPI');
$GLOBALS['ENV_DEBUG'] = false;

$taxa = TurbellarianAPI::get_all_taxa();
$xml = SchemaDocument::get_taxon_xml($taxa);

$resource_path = CONTENT_RESOURCE_LOCAL_PATH . "185.xml";

$OUT = fopen($resource_path, "w+");
fwrite($OUT, $xml);
fclose($OUT);

$elapsed_time_sec = microtime(1)-$timestart;
echo "\n";
echo "elapsed time = $elapsed_time_sec sec              \n";
echo "elapsed time = " . $elapsed_time_sec/60 . " min   \n";
echo "elapsed time = " . $elapsed_time_sec/60/60 . " hr \n";
exit("\n\n Done processing.");

?>

Update connector to have a short version of the reference for text objects.

git-svn-id: d46fe582d22b46b457d3ac1c55a88da2fbe913a1@1416 baf6b65b-9124-4dc3-b1c0-01155b4af546


<?php

namespace PPP\Wikidata;

use Doctrine\Common\Cache\ArrayCache;
use PPP\Module\ModuleEntryPoint;

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

$entryPoint = new ModuleEntryPoint(new WikidataRequestHandler(
	'https://www.wikidata.org/w/api.php',
	'https://wdq.wmflabs.org/api',
	new ArrayCache()
));
$entryPoint->exec();

<?php

namespace PPP\Wikidata;

use Doctrine\Common\Cache\ArrayCache;
use Doctrine\Common\Cache\MemcachedCache;
use Memcached;
use PPP\Module\ModuleEntryPoint;

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

//TODO: configuration system?
$cache = new ArrayCache();

if(class_exists('Memcached')) {
	$memcached = new Memcached();
	if($memcached->addServer('localhost', 11211)) {
		$cache = new MemcachedCache();
		$cache->setMemcached($memcached);
	}
}

$entryPoint = new ModuleEntryPoint(new WikidataRequestHandler(
	'https://www.wikidata.org/w/api.php',
	'https://wdq.wmflabs.org/api',
	$cache
));
$entryPoint->exec();

Use Memcached on localhost as default (and ArrayCache as fallback)

Note: pretty bad. We should write a proper configuration system.


<?php

/**
   Copyright (C) 2010-2016 by the FusionInventory Development Team
   Copyright (C) 2016 Teclib'

   This file is part of Armadito Plugin for GLPI.

   Armadito Plugin for GLPI 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.

   Armadito Plugin for GLPI 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 Armadito Plugin for GLPI. If not, see <http://www.gnu.org/licenses/>.

**/

include_once ("../../../../inc/includes.php");

if (isset($_GET['agent_id'])) { // GET /jobs
   include_once("../../front/communication.php");

   session_destroy();
}
else{
  http_response_code(400);
  header("Content-Type: application/json");
  echo '{ "plugin_response" : { "version": "'.PLUGIN_ARMADITO_VERSION.'", "error": "Invalid request sent to plugin index." }}';
}

?>

<?php

/**
   Copyright (C) 2010-2016 by the FusionInventory Development Team
   Copyright (C) 2016 Teclib'

   This file is part of Armadito Plugin for GLPI.

   Armadito Plugin for GLPI 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.

   Armadito Plugin for GLPI 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 Armadito Plugin for GLPI. If not, see <http://www.gnu.org/licenses/>.

**/

include_once ("../../../../inc/includes.php");

if (isset($_GET['agent_id'])) { // GET /jobs
   include_once("../../front/communication.php");

   $communication  = new PluginArmaditoCommunication();
   $communication->init();

   session_destroy();
}
else{
  http_response_code(400);
  header("Content-Type: application/json");
  echo '{ "plugin_response" : { "version": "'.PLUGIN_ARMADITO_VERSION.'", "error": "Invalid request sent to plugin index." }}';
}

?>

Add load communication in /jobs

Add load communication in /jobs


<?php

class Sabre_VObject_WindowsTimezoneMapTest extends PHPUnit_Framework_TestCase {

    /**
     * @dataProvider getMapping
     */
    function testCorrectTZ($timezoneName) {

        $tz = new DateTimeZone($timezoneName);

    }

    function getMapping() {

        // PHPUNit requires an array of arrays
        return array_map(
            function($value) {
                return array($value);
            },
            Sabre_VObject_WindowsTimeZoneMap::$map
        );

    }

}

<?php

class Sabre_VObject_WindowsTimezoneMapTest extends PHPUnit_Framework_TestCase {

    /**
     * @dataProvider getMapping
     */
    function testCorrectTZ($timezoneName) {

        $tz = new DateTimeZone($timezoneName);

    }

    function getMapping() {

        // PHPUNit requires an array of arrays
        return array_map(
            function($value) {
                return array($value);
            },
            Sabre_VObject_WindowsTimezoneMap::$map
        );

    }

}

Correct casing to fix the travis build

Correct casing to fix the travis build


<?php

final class PhabricatorConfigManagementDoneWorkflow
  extends PhabricatorConfigManagementWorkflow {

  protected function didConstruct() {
    $this
      ->setName('done')
      ->setExamples('**done** __activity__')
      ->setSynopsis(pht('Mark a manual upgrade activity as complete.'))
      ->setArguments(
        array(
          array(
            'name' => 'activities',
            'wildcard' => true,
          ),
        ));
  }

  public function execute(PhutilArgumentParser $args) {
    $activities = $args->getArg('activities');
    if (!$activities) {
      throw new PhutilArgumentUsageException(
        pht('Specify an activity to mark as completed.'));
    }

    foreach ($activities as $type) {
      $activity = id(new PhabricatorConfigManualActivity())->loadOneWhere(
        'activityType = %s',
        $type);
      if (!$activity) {
        throw new PhutilArgumentUsageException(
          pht(
            'Activity "%s" is not currently marked as required, so there '.
            'is no need to complete it.',
            $type));
      } else {
        $activity->delete();
        echo tsprintf(
          "%s\n",
          pht(
            'Marked activity "%s" as completed.',
            $type));
      }
    }

    echo tsprintf(
      "%s\n",
      pht('Done.'));

    return 0;
  }

}

<?php

final class PhabricatorConfigManagementDoneWorkflow
  extends PhabricatorConfigManagementWorkflow {

  protected function didConstruct() {
    $this
      ->setName('done')
      ->setExamples('**done** __activity__')
      ->setSynopsis(pht('Mark a manual upgrade activity as complete.'))
      ->setArguments(
        array(
          array(
            'name' => 'force',
            'short' => 'f',
            'help' => pht(
              'Mark activities complete even if there is no outstanding '.
              'need to complete them.'),
          ),
          array(
            'name' => 'activities',
            'wildcard' => true,
          ),
        ));
  }

  public function execute(PhutilArgumentParser $args) {
    $is_force = $args->getArg('force');

    $activities = $args->getArg('activities');
    if (!$activities) {
      throw new PhutilArgumentUsageException(
        pht('Specify an activity to mark as completed.'));
    }

    foreach ($activities as $type) {
      $activity = id(new PhabricatorConfigManualActivity())->loadOneWhere(
        'activityType = %s',
        $type);
      if (!$activity) {
        if ($is_force) {
          echo tsprintf(
            "%s\n",
            pht(
              'Activity "%s" did not need to be marked as complete.',
              $type));
        } else {
          throw new PhutilArgumentUsageException(
            pht(
              'Activity "%s" is not currently marked as required, so there '.
              'is no need to complete it.',
              $type));
        }
      } else {
        $activity->delete();
        echo tsprintf(
          "%s\n",
          pht(
            'Marked activity "%s" as completed.',
            $type));
      }
    }

    echo tsprintf(
      "%s\n",
      pht('Done.'));

    return 0;
  }

}

Add a "--force" argument to "bin/config done"

Summary:
Ref T11922. When we deploy on Saturday I need to rebuild all the cluster indexes, but some instances won't have anything indexed so they won't actually trigger the activity.

Add a `--force` flag that just clears an activity even if the activity is not required.

Test Plan: Ran `bin/config done reindex --force` several times.

Reviewers: chad

Reviewed By: chad

Maniphest Tasks: T11922

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


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

/**
 * Category Controller Class
 *
 * @author    	Johan Janssens <http://nooku.assembla.com/profile/johanjanssens>
 * @category 	Nooku
 * @package     Nooku_Server
 * @subpackage  Newsfeeds
 */
class ComNewsfeedsControllerCategory extends ComDefaultControllerDefault
{
    protected function _actionGet(KCommandContext $context)
    {
        $view = $this->getView();

	    //Set the layout
        if($view instanceof KViewTemplate)
	    {
	        $layout = clone $view->getIdentifier();
	        $layout->package  = 'categories';
	        $layout->name     = $view->getLayout();

	        //Force re-creation of the filepath to load the category templates
	        $layout->filepath = '';

	        $view->setLayout($layout);
	    }

	    //Set the toolbar
	    if($this->isCommandable()) {
	        $this->setToolbar('admin::com.categories.controller.toolbar.'.$view->getName());
	    }

        return parent::_actionGet($context);
    }

    public function setModel($model)
    {
        $model = parent::setModel($model);
        $model->package = 'categories';

        return $model;
    }

	public function getRequest()
	{
		$this->_request['section'] = 'com_newsfeeds';
	    return $this->_request;
	}
}

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

/**
 * Category Controller Class
 *
 * @author    	Johan Janssens <http://nooku.assembla.com/profile/johanjanssens>
 * @category 	Nooku
 * @package     Nooku_Server
 * @subpackage  Newsfeeds
 */
class ComNewsfeedsControllerCategory extends ComCategoriesControllerCategory
{

}

Extend from new ComCategoriesControllerCategory controller.


<?php

namespace VinceRuby\Tactician\Tests\Stubs;

use VinceRuby\Tactician\Tests\Stubs\TestCommand;

class TestCommandHandler
{
	public function handle(TestCommand $command)
	{
		return true;
	}
}

<?php

namespace VinceRuby\Tactician\Tests\Stubs;

use VinceRuby\Tactician\Tests\Stubs\TestCommand;

class TestCommandHandler
{
	public function handle(TestCommand $command)
	{
		return $command->data;
	}
}

Change test command handler to return what was stored in the test command dto


<?php

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

namespace Composer\Downloader;

use Composer\Package\PackageInterface;

/**
 * Downloader for phar files
 *
 * @author Kirill chEbba Chebunin <iam@chebba.org>
 */
class PharDownloader extends FileDownloader
{
    /**
     * {@inheritDoc}
     */
    protected function extract($file, $path)
    {
        // Can throw an UnexpectedValueException
        $archive = new \Phar($file);
        $archive->extractTo($path);
    }
}

<?php

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

namespace Composer\Downloader;

use Composer\Package\PackageInterface;

/**
 * Downloader for phar files
 *
 * @author Kirill chEbba Chebunin <iam@chebba.org>
 */
class PharDownloader extends FileDownloader
{
    /**
     * {@inheritDoc}
     */
    protected function extract($file, $path)
    {
        // Can throw an UnexpectedValueException
        $archive = new \Phar($file);
        $archive->extractTo($path);
        /* TODO: handle openssl signed phars
         * https://github.com/composer/composer/pull/33#issuecomment-2250768
         * https://github.com/koto/phar-util
         * http://blog.kotowicz.net/2010/08/hardening-php-how-to-securely-include.html
         */
    }
}

Add todo for signed phars

Add todo for signed phars


<?php

namespace Application\Controller\Api;

use Zend\Db\Sql;
use Zend\Db\TableGateway\TableGateway;
use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\View\Model\JsonModel;

class SpecController extends AbstractRestfulController
{
    /**
     * @var TableGateway
     */
    private $table;

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

    private function getSpecOptions(int $parentId = 0): array
    {
        $select = new Sql\Select($this->table->getTable());
        $select->order('name');

        if ($parentId) {
            $select->where([
                'parent_id' => $parentId
            ]);
        } else {
            $select->where(['parent_id is null']);
        }

        $rows = $this->table->selectWith($select);
        $result = [];
        foreach ($rows as $row) {
            $result[] = [
                'id'         => (int)$row['id'],
                'name'       => $row['name'],
                'short_name' => $row['short_name'],
                'childs'     => $this->getSpecOptions($row['id'])
            ];
        }

        return $result;
    }

    public function indexAction()
    {
        if (! $this->user()->inheritsRole('moder')) {
            return $this->forbiddenAction();
        }

        return new JsonModel([
            'items' => $this->getSpecOptions(0),
        ]);
    }
}

<?php

namespace Application\Controller\Api;

use Zend\Db\Sql;
use Zend\Db\TableGateway\TableGateway;
use Zend\Mvc\Controller\AbstractRestfulController;
use Zend\View\Model\JsonModel;

class SpecController extends AbstractRestfulController
{
    /**
     * @var TableGateway
     */
    private $table;

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

    private function getSpecOptions(int $parentId = 0): array
    {
        $select = new Sql\Select($this->table->getTable());
        $select->order('name');

        if ($parentId) {
            $select->where([
                'parent_id' => $parentId
            ]);
        } else {
            $select->where(['parent_id is null']);
        }

        $rows = $this->table->selectWith($select);
        $result = [];
        foreach ($rows as $row) {
            $result[] = [
                'id'         => (int)$row['id'],
                'name'       => $row['name'],
                'short_name' => $row['short_name'],
                'childs'     => $this->getSpecOptions($row['id'])
            ];
        }

        return $result;
    }

    public function indexAction()
    {
        return new JsonModel([
            'items' => $this->getSpecOptions(0),
        ]);
    }
}

Allow get specs to everyone

Allow get specs to everyone


<?php
namespace ComplexPie\RSS20;

class Item extends \ComplexPie\XML\Entry
{
    protected static $static_ext = array();

    protected static $aliases = array(
        'summary' => 'description',
        'published' => 'pubDate',
    );

    protected static $elements = array(
        'description' => array(
            'element' => 'description',
            'contentConstructor' => 'ComplexPie\\Content::from_escaped_html',
            'single' => true
        ),
        'link' => array(
            'element' => 'link',
            'contentConstructor' => 'ComplexPie\\Content\\IRINode',
            'single' => true
        ),
        'title' => array(
            'element' => 'title',
            'contentConstructor' => 'ComplexPie\\Content::from_escaped_html',
            'single' => true
        ),
        'pubDate' => array(
            'element' => 'pubDate',
            'contentConstructor' => 'ComplexPie\\Content::from_date_in_textcontent',
            'single' => true
        ),
    );

    protected static $element_namespaces = array(
    );
}

Item::add_static_extension('get', '\\ComplexPie\\RSS20\\links', ~PHP_INT_MAX);

<?php
namespace ComplexPie\RSS20;

class Item extends \ComplexPie\XML\Entry
{
    protected static $static_ext = array();

    protected static $aliases = array(
        'summary' => 'description',
        'published' => 'pubDate',
    );

    protected static $elements = array(
        // XXX: author
        // XXX: category
        // XXX: comments
        'description' => array(
            'element' => 'description',
            'contentConstructor' => 'ComplexPie\\Content::from_escaped_html',
            'single' => true
        ),
        // XXX: enclosure
        // XXX: guid
        'link' => array(
            'element' => 'link',
            'contentConstructor' => 'ComplexPie\\Content\\IRINode',
            'single' => true
        ),
        'pubDate' => array(
            'element' => 'pubDate',
            'contentConstructor' => 'ComplexPie\\Content::from_date_in_textcontent',
            'single' => true
        ),
        // XXX: source
        'title' => array(
            'element' => 'title',
            'contentConstructor' => 'ComplexPie\\Content::from_escaped_html',
            'single' => true
        ),
    );

    protected static $element_namespaces = array(
    );
}

Item::add_static_extension('get', '\\ComplexPie\\RSS20\\links', ~PHP_INT_MAX);

Add comments about what other elements need support.


<?php declare(strict_types=1);

namespace Tests\Unit\Translator\Framework;

use PHPUnit\Framework\TestCase;

class HelperTest extends TestCase
{
    /** @var string */
    private $testDir;

    protected function setUp(): void
    {
        $this->testDir = realpath(__DIR__.'/../..') ?? '';
    }

    public function testGlobRecursive(): void
    {
        $fixturesDir = realpath("{$this->testDir}/Fixtures/Glob");

        $files = glob_recursive("{$fixturesDir}/*.txt", GLOB_BRACE);

        $this->assertEquals([
            '/Fixtures/Glob/file1.txt',
            '/Fixtures/Glob/file2.txt',
            '/Fixtures/Glob/SubDir/SubDirFile1.txt',
            '/Fixtures/Glob/SubDir/SubDirFile2.txt',
            '/Fixtures/Glob/SubDir/SubDir2/SubDir2file1.txt',
            '/Fixtures/Glob/SubDir/SubDir2/SubDir2file2.txt',
        ], $this->removeRelativePath($files));
    }

    /**
     * @param string[] $files
     * @return string[]
     */
    private function removeRelativePath(array $files): array
    {
        return array_map(function (string $file): string {
            return str_replace($this->testDir, '', $file);
        }, $files);
    }
}

<?php declare(strict_types=1);

namespace Tests\Unit\Translator\Framework;

use PHPUnit\Framework\TestCase;

class HelperTest extends TestCase
{
    /** @var string */
    private $testDir;

    protected function setUp(): void
    {
        $this->testDir = realpath(__DIR__.'/../..') ?? '';
    }

    public function testGlobRecursive(): void
    {
        $fixturesDir = realpath("{$this->testDir}/Fixtures/Glob");

        $files = glob_recursive("{$fixturesDir}/*.txt", GLOB_BRACE);

        $this->assertEquals([
            '/Fixtures/Glob/file1.txt',
            '/Fixtures/Glob/file2.txt',
            '/Fixtures/Glob/SubDir/SubDirFile1.txt',
            '/Fixtures/Glob/SubDir/SubDirFile2.txt',
            '/Fixtures/Glob/SubDir/SubDir2/SubDir2file1.txt',
            '/Fixtures/Glob/SubDir/SubDir2/SubDir2file2.txt',
        ], $this->replaceDirectorySeparators($this->removeRelativePath($files)));
    }

    /**
     * @param string[] $files
     * @return string[]
     */
    private function removeRelativePath(array $files): array
    {
        return array_map(function (string $file): string {
            return str_replace($this->testDir, '', $file);
        }, $files);
    }

    /**
     * @param string[] $files
     * @return string[]
     */
    private function replaceDirectorySeparators(array $files): array
    {
        return array_map(function (string $file): string {
            return str_replace('\\', '/', $file);
        }, $files);
    }
}

Fix running unit tests on Windows

Fix running unit tests on Windows