How can i do this right? PHP5 Form validation - php

I'm trying to set my first steps into the OO PHP world. What I'm trying to do is make a class that validates my form input. I know what input fields I need in my entire website and want to make a switch, to do the right thing based on the input field. Lets say we have the input field named 'email', and we have a form for that etc...
First, what I want to do is try to read the $_post names with array_key() function, based on that I have a switch.
Here is my code:
public function __construct ( $var ) {
$this->arraykeys = array_keys($var);
$this->error = false;
$this->message = array();
}
public function check() {
foreach ($this->arraykeys as $i => $value)
{
switch ($value)
{
case 'email' :
$checkmail = new checkEmail($_POST);
$checkmail->chkEmail($_POST['email']);
if ($checkmail->chkEmail($_POST['email']) == false)
{
array_push($this->message, 'Cannot validate emailadres');
}
break;
}
}
// print_r($this->field);
}
The check works, but somehow the message array stays empty after an error!
I tried everything, but I just can't get it on to the screen!
Please help!
Thanks!!

Before you make use of OOP you actually need to have some of the more basic objects that enable you to let your form processing come to live, for example object oriented validation of form fields within PHP superglobals with error messages:
Just exemplary:
// defining the interfaces and classes of the form values and validation, form field
// and fields
Interface FormValue
{
public function getValue();
}
interface FormValueValidator
{
/**
* #param FormValue $value
* #return bool
*/
public function validate(FormValue $value);
}
class NamedFormValue implements FormValue
{
private $name;
private $value;
public function __construct(array $data, $name, $default = null)
{
$this->name = $name;
$this->value = isset($data[$name]) ? $data[$name] : $default;
}
public function getValue()
{
return $this->value;
}
public function getName()
{
return $this->name;
}
}
class EmailValidator implements FormValueValidator
{
public function validate(FormValue $value)
{
$result = filter_var((string) $value->getValue(), FILTER_VALIDATE_EMAIL);
return is_string($result);
}
}
class FormFieldFactory
{
/**
* #param $name
* #param array $field
* #return FormField
*/
public function create($name, array $field)
{
$validatorClass = sprintf('%sValidator', #$field['validator']);
$validator = new $validatorClass;
$formField = new FormField($name);
$formField->setValidator($validator);
$formField->setErrorMessage($field['error_msg']);
return $formField;
}
}
class FormField
{
private $name;
/**
* #var FormValueValidator
*/
private $validator;
private $errorMessage;
/**
* #var FormValue
*/
private $value;
public function __construct($name)
{
$this->name = $name;
}
public function setValidator(FormValueValidator $validator)
{
$this->validator = $validator;
}
public function isValid()
{
return $this->validator->validate($this->value);
}
public function setErrorMessage($errorMessage)
{
$this->errorMessage = $errorMessage;
}
public function getErrorMessage() {
return $this->errorMessage;
}
public function setValue(FormValue $value)
{
$this->value = $value;
}
/**
* #return FormValue
*/
public function getValue()
{
return $this->value;
}
}
class FormFields extends IteratorIterator
{
private $fieldFactory;
private $invalidFields;
public function __construct(array $definitions, $fieldFactory)
{
parent::__construct(new ArrayIterator($definitions));
$this->fieldFactory = $fieldFactory;
}
public function current()
{
$name = $this->getInnerIterator()->key();
$definition = $this->getInnerIterator()->current();
return $this->fieldFactory->create($name, $definition);
}
public function valid()
{
return $this->getInnerIterator()->valid();
}
/**
* #param array $data
* #return bool true on success, false on validation error
*/
public function validateOn(array $data)
{
$this->invalidFields = array();
foreach($this as $name => $field) {
/* #var $field FormField */
$value = new NamedFormValue($data, $name);
$field->setValue($value);
$valid = $field->isValid();
$valid || ($this->invalidFields[$name] = $field);
}
return 0 === count($this->invalidFields);
}
/**
* #return FormField[]
*/
public function getInvalidFields()
{
return $this->invalidFields;
}
}
// defining the form in array notation:
$form = array(
'fields' => array(
'email' => array(
'validator' => 'Email',
'error_msg' => 'Cannot validate emailadress',
),
),
);
// processing the form validation
$messages = array();
$fields = new FormFields($form['fields'], new FormFieldFactory());
$fields->validateOn($_POST)
foreach ($fields->getInvalidFields() as $field) {
$messages[] = $field->getErrorMessage();
}
var_dump($messages);
Exemplary output:
array(1) {
[0]=>
string(27) "Cannot validate emailadress"
}

Try this instead :
public function check()
{
foreach ($this->arraykeys as $i => $value)
{
switch ($value)
{
case 'email' :
$checkmail = new checkEmail($_POST);
$checkmail->chkEmail($_POST['email']);
if ($checkmail->chkEmail($_POST['email']) == false)
{
$this->message[] = 'Cannot validate emailadres';
}
break;
}
}
print_r($this->message);
}
Also be sure your property is set to public.
Are you sure $checkmail->chkEmail() is getting false and is working well ?

Related

PhP foreach through class instances

I'm wondering about this weird thing:
public function getAllCustomers()
{
$customers = $this->redis->keys("customer:*");
foreach ($customers as $value) {
return new \Customer($this->redis->hget($value,"name"),$this->redis->hget($value,"id"),$this->redis->hget($value,"email"));
}
}
This method returns all customers from my database.
But if I try to loop through all of these customers:
foreach ($customerController->getAllCustomers() as $customer) {
var_dump($customer);
}
The getName() method is not found. var_dump returns:
NULL
NULL
NULL
Customer class:
class Customer {
var $name;
var $id;
var $email;
function __construct($name, $id,$email) {
$this->name = $name;
$this->id = $id;
$this->email = $email;
}
/**
* #return mixed
*/
public function getName()
{
return $this->name;
}
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
/**
* #return mixed
*/
public function getEmail()
{
return $this->email;
}
public function __toString()
{
return "";
}
}
I'm pretty new to PHP and don't understand why I can't access the Customer object's field.
Your Problem: you do not return array of customer but only one. You getting null because your function return only 1 object -> and in PHP, when using foreach loop on object you get his fields -> and the fields do not have the getName function.
Solution: Init customer array, populate it and return from the function.
public function getAllCustomers()
{
$customers = $this->redis->keys("customer:*");
$customersObjs = array();
foreach ($customers as $value) {
$customersObjs[] = new Customer($this->redis->hget($value,"name"),$this->redis->hget($value,"id"),$this->redis->hget($value,"email")));
}
return $customersObjs;
}
Now you have array of the customersObjs you can loop on with:
foreach ($customerController->getAllCustomers() as $customer) {
echo $customer->getName();
}
Solution :
public function getAllCustomers()
{
$customers = $this->redis->keys("customer:*");
$custumersArray = array();
foreach ($customers as $value) {
$custumersArray[] = \Customer($this->redis->hget($value,"name"),$this->redis->hget($value,"email"),$this->redis->hget($value,"id"));
}
return $custumersArray;
}
the problem was that you are returning a single array but not a array list.

php class method within method

If I want to access the public method, I can do that easily. But if I want to access the property within method, what should I do, and is it recommended??
Can I do something like this in php?
class Auth {
public function check($user = false){
$project = false; //make it somehow public
if($user == 'user1'){
$this->project = 1;
}
}
}
and than in some other place
$auth = new Auth();
$auth->check('user1')->project;
Just so you people know its possible here is the Zend framework code from
Zend-Authentication
if ($result->isValid()) {
$this->getStorage()->write($result->getIdentity());
}
I believe your question is basically regarding Fluent Interfaces or Method Chaining in conjunction with the magic method __get
Attempting to run this:
<?php
class Auth {
public function check($user = false){
$project = false; //make it somehow public
if($user == 'user1'){
$this->project = 1;
}
}
}
$auth = new Auth();
$auth->check('user1')->project;
Results in:
Notice: Trying to get property of non-object in /in/Hi5Rc on line 13
because $auth->check('user1') returns NULL (or void) and NULL doesn't have a project property.
The first thing we require is for $auth->check('user1') to return something useful. Given that $project is a boolean and $this->project is an integer, it makes the most sense to just return $project and get the value.
<?php
class Auth {
public function check($user = false){
$project = false; //make it somehow public
if($user == 'user1'){
$this->project = 1;
}
return $project;
}
}
$auth = new Auth();
print_r($auth->check('user1'));
which results in :
bool(false)
But that doesn't address your question about how to fluently access a nonpublic field or parameter.
It appears that you are operating under the misconception that these projects are taking method scoped variables like $project in your check() class and making them accessible. They are not.
Not even in your example of the Zend-Authentication.
The field $storage itself is protected, but it has public (fluent) getters/setters.
So, $this->getStorage() returns an instance of new Storage\Session() which has a public write().
Thus $this->getStorage()->write() works.
So lets take your example class and modify it a bit to demonstrate.
<?php
class Project{
/**
* #var string
*/
private $name;
/**
* #var bool
*/
private $active;
/**
* #var string
*/
private $description;
public function __construct($name = 'Default', $active = false, $description = '')
{
$this->name = $name;
$this->active = $active;
$this->description = $description;
}
/**
* #param string $name
*
* #return Project
*/
public function setName(string $name): Project
{
$this->name = $name;
return $this;
}
/**
* #param bool $active
*
* #return Project
*/
public function setActive(bool $active): Project
{
$this->active = $active;
return $this;
}
/**
* #param string $description
*
* #return Project
*/
public function setDescription(string $description): Project
{
$this->description = $description;
return $this;
}
/**
* #return string
*/
public function getName(): string
{
return $this->name;
}
/**
* #return bool
*/
public function isActive(): bool
{
return $this->active;
}
/**
* #return string
*/
public function getDescription(): string
{
return $this->description;
}
public function toArray(){
return [
'name' => $this->name,
'active' => $this->active,
'description' => $this->description
];
}
public function toJson(){
return json_encode($this->toArray());
}
public function __toString()
{
return $this->toJson();
}
}
class Auth {
/**
* #var Project
*/
private $project;
public function __construct($project = Null)
{
$this->project = is_null($project)? new Project() : $project;
}
public function check($user = false){
if($user == 'user1'){
$this->project->setName("Project: $user")->setActive(true)->setDescription("This project belongs to $user");
}
return $this;
}
/**
* #param Project $project
*
* #return Auth
*/
public function setProject(Project $project): Auth
{
$this->project = $project;
return $this;
}
/**
* #return Project
*/
public function getProject(): Project
{
return $this->project;
}
}
$auth = new Auth();
echo $auth->check('user1')->getProject();
now results in:
{"name":"Project: user1","active":true,"description":"This project
belongs to user1"}
However, you wanted to access the private field as if it were a public field without using a defined getter/setter. So lets make some more changes to the Auth class.
class Auth {
/**
* #var Project[]
*/
private $private_project;
public function __construct($project = Null)
{
$this->private_project = is_null($project)? new Project() : $project;
}
public function check($user = false){
if($user == 'user1'){
$this->private_project->setName("Project: $user")->setActive(true)->setDescription("This project belongs to $user");
}
return $this;
}
public function __get($name)
{
if ($name === 'project'){
return $this->private_project;
}
}
}
Now you can fluently access the field as you requested:
$auth = new Auth();
echo $auth->check('baduser')->project;
echo "\n";
echo $auth->check('user1')->project;
results in:
{"name":"Default","active":false,"description":""}
{"name":"Project: user1","active":true,"description":"This project belongs to user1"}
Laravel's Eloquent models make great use of the __get()function for accessing model fields dynamically. Laravel also makes great use of the __call() magic method for fluency.
I hope that helps bring some clarity.
class Auth
{
protected $project;
public function __constructor($project = false)
{
$this->project = $project;
}
public function check($user = false)
{
if($user == 'user1')
{
$this->project = 1;
}
return $this;
}
public function project()
{
return $this->project;
}
}
then you can do the following:
$auth = new Auth();
$auth->check('user1')->project(); // returns 1
or if you want you can also set another default value for the $projectin the constructor
$auth = new Auth($other_default_value);
$auth->check('user2')->project(); // returns $other_default_value
If you don't want to create extra class properties and "preserve method chaining", what about yield?
class Auth
{
public function check($user = false)
{
$project = false; // make it somehow public
if($user === 'user1'){
(yield 'project' => $project); // making it public
}
return $this;
}
}
Later on you can discover it as follows:
$array = iterator_to_array($auth->check($user));
// array(1) { ["project"] => bool(false) }
But for this to use you won't be able to use method chaining, bec. you need to retrieve generator anyway, so better to revise approach for discovering the $project.
<?php
class Auth
{
public $project;
public function check($user = false)
{
$this->project = false;//make it somehow public
if ($user == 'user1') {
$this->project = 1;
}
return $this;
}
}
$auth = new Auth();
var_dump($auth->check('user1')->project);
This will return you 1. The local variables defined in function are only accessbile inside the function not outside hence you need to define them globally
$project is a local variable in your case, visible within the scope of the check method. You could define it as a member:
class Auth {
public $project = false;
public function check($user = false){
if($user == 'user1'){
$this-project = 1;
}
}
}
However, it is recommendable to make the member public and reach it via a getter, which will check whether it was initialized and if not, initialize it:
class Auth {
private $project = false;
public getProject($user = false) {
if ($this->project === false) {
check($user);
}
return $this->project;
}
public function check($user = false){
if($user == 'user1'){
$this-project = 1;
}
}
}
You will need to add it as a class variable:
class Auth {
public $project = false;
public function check($user = false) {
if($user == 'user1'){
$this->project = 1;
}
}
}
The property is then available as follows:
$auth = new Auth ();
$auth->check ('user1');
echo $auth->project; // 1

Function and variables issue

I have a problem.. When I execute this code:
public function korisnici(){
$modelk = new Korisnici();
$upit = $modelk::find()->asArray()->orderBy('id DESC')->all();
$items = [];
foreach ($upit as $key => $value) {
foreach ($value as $kljuc => $vrijednost){
$items[] = [$kljuc => $vrijednost];
}
}
return $items;
}
private static $users = $this->korisnici();
It gives me this error: syntax error, unexpected '$this' (T_VARIABLE)..
Can someone help me, how can I call this function?
Here's my whole class:
class User extends \yii\base\Object implements \yii\web\IdentityInterface
{
public $id;
public $username;
public $password;
public $authKey;
public $accessToken;
public $arr;
public function korisnici(){
$modelk = new Korisnici();
$upit = $modelk::find()->asArray()->orderBy('id DESC')->all();
$items = [];
foreach ($upit as $key => $value) {
foreach ($value as $kljuc => $vrijednost){
$items[] = [$kljuc => $vrijednost];
}
}
return $items;
}
public $users = $this->korisnici();
/**
* #inheritdoc
*/
public static function findIdentity($id)
{
return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
}
/**
* #inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
foreach (self::$users as $user) {
if ($user['accessToken'] === $token) {
return new static($user);
}
}
return null;
}
/**
* Finds user by username
*
* #param string $username
* #return static|null
*/
public static function findByUsername($username)
{
foreach (self::$users as $user) {
if (strcasecmp($user['username'], $username) === 0) {
return new static($user);
}
}
return null;
}
/**
* #inheritdoc
*/
public function getId()
{
return $this->id;
}
/**
* #inheritdoc
*/
public function getAuthKey()
{
return $this->authKey;
}
/**
* #inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->authKey === $authKey;
}
/**
* Validates password
*
* #param string $password password to validate
* #return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return $this->password === $password;
}
}
I'm trying to change this default model from Yii Framework so I can login using database...
Looks like you have copied it from a class. The following will work like a regular function. Still not sure where you get $modelk = new Korisnici(); from
function korisnici(){
$modelk = new Korisnici();
$upit = $modelk::find()->asArray()->orderBy('id DESC')->all();
$items = [];
foreach ($upit as $key => $value) {
foreach ($value as $kljuc => $vrijednost){
$items[] = [$kljuc => $vrijednost];
}
}
return $items;
}
print_r(korisnici());
EDIT: After looking at your whole class:
You need to use the __construct method.
public function __construct()
{
$this->users = $this->korisnici();
}

Update a record through model in zend framework

I am having a model and would need to update the record. every time $count ($count = $post->save()) is being NULL. how is it possible to know whether this record saved or not. if saved, i want to display the following message 'Post updated' and if not the other message 'Post cannot update'.
This is always going to the else port. how can i know model updated correctly or not?
$post = new Application_Model_Post($form->getValues());
$post->setId($id);
$count = $post->save();
//var_dump($count); exit;
if ($count > 0) {
$this->_helper->flashMessenger->addMessage('Post updated');
} else {
$this->_helper->flashMessenger->addMessage('Post cannot update');
}
Application_Model_Post code is as below,
class Application_Model_Post
{
/**
* #var int
*/
protected $_id;
/**
* #var string
*/
protected $_title;
/**
* #var string
*/
protected $_body;
/**
* #var string
*/
protected $_created;
/**
* #var string
*/
protected $_updated;
/**
* #var Application_Model_PostMapper
*/
protected $_mapper;
/**
* Class Constructor.
*
* #param array $options
* #return void
*/
public function __construct(array $options = null)
{
if (is_array($options)) {
$this->setOptions($options);
}
}
public function setOptions(array $options)
{
$methods = get_class_methods($this);
foreach ($options as $key=> $value) {
$method = 'set'.ucfirst($key);
if (in_array($method, $methods)) {
$this->$method($value);
}
}
return $this;
}
public function setId($id)
{
$this->_id = $id;
return $this;
}
public function getId()
{
return $this->_id;
}
public function setTitle($title)
{
$this->_title = (string) $title;
return $this;
}
public function getTitle()
{
return $this->_title;
}
public function setBody($body)
{
$this->_body = $body;
return $this;
}
public function getBody()
{
return $this->_body;
}
public function setCreated($ts)
{
$this->_created = $ts;
return $this;
}
public function getCreated()
{
return $this->_created;
}
/**
* Set data mapper.
*
* #param mixed $mapper
* #return Application_Model_Post
*/
public function setMapper($mapper)
{
$this->_mapper = $mapper;
return $this;
}
/**
* Get data mapper.
*
* Lazy loads Application_Model_PostMapper instance if no mapper
* registered.
*
* #return Application_Model_PostMapper
*/
public function getMapper()
{
if (null === $this->_mapper) {
$this->setMapper(new Application_Model_PostMapper());
}
return $this->_mapper;
}
/**
* Save the current post.
*
* #return void
*/
public function save()
{
$this->getMapper()->save($this);
}
public function getPost($id)
{
return $this->getMapper()->getPost($id);
}
/**
* Update the current post.
*
* #return void
*/
public function update($data, $where)
{
$this->getMapper()->update($data, $where);
}
/**
* Find a post.
*
* Resets entry state if matching id found.
*
* #param int $id
* #return Application_Model_Post
*/
public function find($id)
{
$this->getMapper()->find($id, $this);
return $this;
}
/**
* Fetch all posts.
*
* #return array
*/
public function fetchAll()
{
return $this->getMapper()->fetchAll();
}
}
getMapper refers to the class Application_Model_PostMapper.
class Application_Model_PostMapper
{
public function save(Application_Model_Post $post)
{
$data = array(
'title'=>$post->getTitle(),
'body'=>$post->getBody(),
'created'=>$post->getCreated()
);
if (null === ($id = $post->getId())) {
unset($data['id']);
$data['created'] = date('Y-m-d H:i:s');
$post->setId($this->getDbTable()->insert($data));
} else {
$this->getDbTable()->update($data, array('id = ?'=>$id));
}
}
public function getDbTable()
{
if (null === $this->_dbTable) {
$this->setDbTable('Application_Model_DbTable_Post');
}
return $this->_dbTable;
}
}
Class of Application_Model_DbTable_Post
class Application_Model_DbTable_Post extends Zend_Db_Table_Abstract
{
protected $_name = 'posts';
}
Let me know if anything is incorrect. i am a newbie to zend and did thsi while referring the zend site. http://framework.zend.com/manual/1.12/en/learning.quickstart.create-model.html
you can extend your script like this. zend dbtable triggers the Zend_Db_Exception on any error during any insert or update.
class Application_Model_PostMapper
{
public function save(Application_Model_Post $post)
{
$data = array(
'title'=>$post->getTitle(),
'body'=>$post->getBody(),
'created'=>$post->getCreated()
);
try {
if (null === ($id = $post->getId())) {
unset($data['id']);
$data['created'] = date('Y-m-d H:i:s');
$post->setId($this->getDbTable()->insert($data));
} else {
$this->getDbTable()->update($data, array('id = ?'=>$id));
}
} catch (Zend_Db_Exception $e) {
// error thrown by dbtable class
return $e->getMessage();
}
// no error
return true;
}
}
now you can check like this
$post = new Application_Model_Post($form->getValues());
$post->setId($id);
$isSaved = $post->save();
if ($isSaved === true) {
$this->_helper->flashMessenger->addMessage('Post updated');
} else {
// error
// $isSaved holds the error message
$this->_helper->flashMessenger->addMessage('Post cannot update');
}

Fatal error: Declaration of registerContainerConfiguration must be compatible with that of Kernel::registerContainerConfiguration

Do anyone know why this occurs?
as far I can get, the child class method is declared in the same way as parent's.
Thanks!
here is my kernel code:
<?php
require_once __DIR__.'/../src/autoload.php';
use Symfony\Framework\Kernel;
use Symfony\Components\DependencyInjection\Loader\YamlFileLoader as ContainerLoader;
use Symfony\Components\Routing\Loader\YamlFileLoader as RoutingLoader;
use Symfony\Framework\KernelBundle;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Bundle\ZendBundle\ZendBundle;
use Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle;
use Symfony\Bundle\DoctrineBundle\DoctrineBundle;
use Symfony\Bundle\DoctrineMigrationsBundle\DoctrineMigrationsBundle;
use Symfony\Bundle\DoctrineMongoDBBundle\DoctrineMongoDBBundle;
use Symfony\Bundle\PropelBundle\PropelBundle;
use Symfony\Bundle\TwigBundle\TwigBundle;
use Application\UfaraBundle\UfaraBundle;
class UfaraKernel extends Kernel {
public function registerRootDir() {
return __DIR__;
}
public function registerBundles() {
$bundles = array(
new KernelBundle(),
new FrameworkBundle(),
new ZendBundle(),
new SwiftmailerBundle(),
new DoctrineBundle(),
//new DoctrineMigrationsBundle(),
//new DoctrineMongoDBBundle(),
//new PropelBundle(),
//new TwigBundle(),
new UfaraBundle(),
);
if ($this->isDebug()) {
}
return $bundles;
}
public function registerBundleDirs() {
$bundles = array(
'Application' => __DIR__.'/../src/Application',
'Bundle' => __DIR__.'/../src/Bundle',
'Symfony\\Framework' => __DIR__.'/../src/vendor/symfony/src/Symfony/Framework',
'Symfony\\Bundle' => __DIR__.'/../src/vendor/symfony/src/Symfony/Bundle',
);
return $bundles;
}
public function registerContainerConfiguration(LoaderInterface $loader) {
return $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
public function registerRoutes() {
$loader = new RoutingLoader($this->getBundleDirs());
return $loader->load(__DIR__.'/config/routing.yml');
}
}
here is the parent class code:
<?php
namespace Symfony\Framework;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
use Symfony\Component\DependencyInjection\Resource\FileResource;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\DependencyInjection\Loader\DelegatingLoader;
use Symfony\Component\DependencyInjection\Loader\LoaderResolver;
use Symfony\Component\DependencyInjection\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\DependencyInjection\Loader\IniFileLoader;
use Symfony\Component\DependencyInjection\Loader\PhpFileLoader;
use Symfony\Component\DependencyInjection\Loader\ClosureLoader;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Framework\ClassCollectionLoader;
/*
* 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.
*/
/**
* The Kernel is the heart of the Symfony system. It manages an environment
* that can host bundles.
*
* #author Fabien Potencier <fabien.potencier#symfony-project.org>
*/
abstract class Kernel implements HttpKernelInterface, \Serializable
{
protected $bundles;
protected $bundleDirs;
protected $container;
protected $rootDir;
protected $environment;
protected $debug;
protected $booted;
protected $name;
protected $startTime;
protected $request;
const VERSION = '2.0.0-DEV';
/**
* Constructor.
*
* #param string $environment The environment
* #param Boolean $debug Whether to enable debugging or not
*/
public function __construct($environment, $debug)
{
$this->environment = $environment;
$this->debug = (Boolean) $debug;
$this->booted = false;
$this->rootDir = realpath($this->registerRootDir());
$this->name = basename($this->rootDir);
if ($this->debug) {
ini_set('display_errors', 1);
error_reporting(-1);
$this->startTime = microtime(true);
} else {
ini_set('display_errors', 0);
}
}
public function __clone()
{
if ($this->debug) {
$this->startTime = microtime(true);
}
$this->booted = false;
$this->container = null;
$this->request = null;
}
abstract public function registerRootDir();
abstract public function registerBundles();
abstract public function registerBundleDirs();
abstract public function registerContainerConfiguration(LoaderInterface $loader);
/**
* Checks whether the current kernel has been booted or not.
*
* #return boolean $booted
*/
public function isBooted()
{
return $this->booted;
}
/**
* Boots the current kernel.
*
* This method boots the bundles, which MUST set
* the DI container.
*
* #throws \LogicException When the Kernel is already booted
*/
public function boot()
{
if (true === $this->booted) {
throw new \LogicException('The kernel is already booted.');
}
if (!$this->isDebug()) {
require_once __DIR__.'/bootstrap.php';
}
$this->bundles = $this->registerBundles();
$this->bundleDirs = $this->registerBundleDirs();
$this->container = $this->initializeContainer();
// load core classes
ClassCollectionLoader::load(
$this->container->getParameter('kernel.compiled_classes'),
$this->container->getParameter('kernel.cache_dir'),
'classes',
$this->container->getParameter('kernel.debug'),
true
);
foreach ($this->bundles as $bundle) {
$bundle->setContainer($this->container);
$bundle->boot();
}
$this->booted = true;
}
/**
* Shutdowns the kernel.
*
* This method is mainly useful when doing functional testing.
*/
public function shutdown()
{
$this->booted = false;
foreach ($this->bundles as $bundle) {
$bundle->shutdown();
$bundle->setContainer(null);
}
$this->container = null;
}
/**
* Reboots the kernel.
*
* This method is mainly useful when doing functional testing.
*
* It is a shortcut for the call to shutdown() and boot().
*/
public function reboot()
{
$this->shutdown();
$this->boot();
}
/**
* Gets the Request instance associated with the master request.
*
* #return Request A Request instance
*/
public function getRequest()
{
return $this->request;
}
/**
* Handles a request to convert it to a response by calling the HttpKernel service.
*
* #param Request $request A Request instance
* #param integer $type The type of the request (one of HttpKernelInterface::MASTER_REQUEST or HttpKernelInterface::SUB_REQUEST)
* #param Boolean $raw Whether to catch exceptions or not
*
* #return Response $response A Response instance
*/
public function handle(Request $request = null, $type = HttpKernelInterface::MASTER_REQUEST, $raw = false)
{
if (false === $this->booted) {
$this->boot();
}
if (null === $request) {
$request = $this->container->get('request');
} else {
$this->container->set('request', $request);
}
if (HttpKernelInterface::MASTER_REQUEST === $type) {
$this->request = $request;
}
$response = $this->container->getHttpKernelService()->handle($request, $type, $raw);
$this->container->set('request', $this->request);
return $response;
}
/**
* Gets the directories where bundles can be stored.
*
* #return array An array of directories where bundles can be stored
*/
public function getBundleDirs()
{
return $this->bundleDirs;
}
/**
* Gets the registered bundle names.
*
* #return array An array of registered bundle names
*/
public function getBundles()
{
return $this->bundles;
}
/**
* Checks if a given class name belongs to an active bundle.
*
* #param string $class A class name
*
* #return Boolean true if the class belongs to an active bundle, false otherwise
*/
public function isClassInActiveBundle($class)
{
foreach ($this->bundles as $bundle) {
$bundleClass = get_class($bundle);
if (0 === strpos($class, substr($bundleClass, 0, strrpos($bundleClass, '\\')))) {
return true;
}
}
return false;
}
/**
* Returns the Bundle name for a given class.
*
* #param string $class A class name
*
* #return string The Bundle name or null if the class does not belongs to a bundle
*/
public function getBundleForClass($class)
{
$namespace = substr($class, 0, strrpos($class, '\\'));
foreach (array_keys($this->getBundleDirs()) as $prefix) {
if (0 === $pos = strpos($namespace, $prefix)) {
return substr($namespace, strlen($prefix) + 1, strpos($class, 'Bundle\\') + 7);
}
}
}
public function getName()
{
return $this->name;
}
public function getSafeName()
{
return preg_replace('/[^a-zA-Z0-9_]+/', '', $this->name);
}
public function getEnvironment()
{
return $this->environment;
}
public function isDebug()
{
return $this->debug;
}
public function getRootDir()
{
return $this->rootDir;
}
public function getContainer()
{
return $this->container;
}
public function getStartTime()
{
return $this->debug ? $this->startTime : -INF;
}
public function getCacheDir()
{
return $this->rootDir.'/cache/'.$this->environment;
}
public function getLogDir()
{
return $this->rootDir.'/logs';
}
protected function initializeContainer()
{
$class = $this->getSafeName().ucfirst($this->environment).($this->debug ? 'Debug' : '').'ProjectContainer';
$location = $this->getCacheDir().'/'.$class;
$reload = $this->debug ? $this->needsReload($class, $location) : false;
if ($reload || !file_exists($location.'.php')) {
$this->buildContainer($class, $location.'.php');
}
require_once $location.'.php';
$container = new $class();
$container->set('kernel', $this);
return $container;
}
public function getKernelParameters()
{
$bundles = array();
foreach ($this->bundles as $bundle) {
$bundles[] = get_class($bundle);
}
return array_merge(
array(
'kernel.root_dir' => $this->rootDir,
'kernel.environment' => $this->environment,
'kernel.debug' => $this->debug,
'kernel.name' => $this->name,
'kernel.cache_dir' => $this->getCacheDir(),
'kernel.logs_dir' => $this->getLogDir(),
'kernel.bundle_dirs' => $this->bundleDirs,
'kernel.bundles' => $bundles,
'kernel.charset' => 'UTF-8',
'kernel.compiled_classes' => array(),
),
$this->getEnvParameters()
);
}
protected function getEnvParameters()
{
$parameters = array();
foreach ($_SERVER as $key => $value) {
if ('SYMFONY__' === substr($key, 0, 9)) {
$parameters[strtolower(str_replace('__', '.', substr($key, 9)))] = $value;
}
}
return $parameters;
}
protected function needsReload($class, $location)
{
if (!file_exists($location.'.meta') || !file_exists($location.'.php')) {
return true;
}
$meta = unserialize(file_get_contents($location.'.meta'));
$time = filemtime($location.'.php');
foreach ($meta as $resource) {
if (!$resource->isUptodate($time)) {
return true;
}
}
return false;
}
protected function buildContainer($class, $file)
{
$parameterBag = new ParameterBag($this->getKernelParameters());
$container = new ContainerBuilder($parameterBag);
foreach ($this->bundles as $bundle) {
$bundle->registerExtensions($container);
if ($this->debug) {
$container->addObjectResource($bundle);
}
}
if (null !== $cont = $this->registerContainerConfiguration($this->getContainerLoader($container))) {
$container->merge($cont);
}
$container->freeze();
foreach (array('cache', 'logs') as $name) {
$dir = $container->getParameter(sprintf('kernel.%s_dir', $name));
if (!is_dir($dir)) {
if (false === #mkdir($dir, 0777, true)) {
die(sprintf('Unable to create the %s directory (%s)', $name, dirname($dir)));
}
} elseif (!is_writable($dir)) {
die(sprintf('Unable to write in the %s directory (%s)', $name, $dir));
}
}
// cache the container
$dumper = new PhpDumper($container);
$content = $dumper->dump(array('class' => $class));
if (!$this->debug) {
$content = self::stripComments($content);
}
$this->writeCacheFile($file, $content);
if ($this->debug) {
$container->addObjectResource($this);
// save the resources
$this->writeCacheFile($this->getCacheDir().'/'.$class.'.meta', serialize($container->getResources()));
}
}
protected function getContainerLoader(ContainerInterface $container)
{
$resolver = new LoaderResolver(array(
new XmlFileLoader($container, $this->getBundleDirs()),
new YamlFileLoader($container, $this->getBundleDirs()),
new IniFileLoader($container, $this->getBundleDirs()),
new PhpFileLoader($container, $this->getBundleDirs()),
new ClosureLoader($container),
));
return new DelegatingLoader($resolver);
}
/**
* Removes comments from a PHP source string.
*
* We don't use the PHP php_strip_whitespace() function
* as we want the content to be readable and well-formatted.
*
* #param string $source A PHP string
*
* #return string The PHP string with the comments removed
*/
static public function stripComments($source)
{
if (!function_exists('token_get_all')) {
return $source;
}
$output = '';
foreach (token_get_all($source) as $token) {
if (is_string($token)) {
$output .= $token;
} elseif (!in_array($token[0], array(T_COMMENT, T_DOC_COMMENT))) {
$output .= $token[1];
}
}
// replace multiple new lines with a single newline
$output = preg_replace(array('/\s+$/Sm', '/\n+/S'), "\n", $output);
// reformat {} "a la python"
$output = preg_replace(array('/\n\s*\{/', '/\n\s*\}/'), array(' {', ' }'), $output);
return $output;
}
protected function writeCacheFile($file, $content)
{
$tmpFile = tempnam(dirname($file), basename($file));
if (false !== #file_put_contents($tmpFile, $content) && #rename($tmpFile, $file)) {
chmod($file, 0644);
return;
}
throw new \RuntimeException(sprintf('Failed to write cache file "%s".', $file));
}
public function serialize()
{
return serialize(array($this->environment, $this->debug));
}
public function unserialize($data)
{
list($environment, $debug) = unserialize($data);
$this->__construct($environment, $debug);
}
}
Your answer lies in the imported namespaces. In the Kernel's file, there's this use clause:
use Symfony\Component\DependencyInjection\Loader\LoaderInterface;
So that ties LoaderInterface to the fully namespaced class Symfony\Component\DependencyInjection\Loader\LoaderInterface.
Basically making the signature:
public function registerContainerConfiguration(Symfony\Component\DependencyInjection\Loader\LoaderInterface $loader);
In your class, you don't import that namespace. So PHP by default assumes the class is in your namespace (since none of the imported namespaces have that interface name).
So your signature is (since you don't declare a namespace):
public function registerContainerConfiguration(\LoaderInterface $loader);
So to get them to match, simply add the use line to the top of your file:
use Symfony\Component\DependencyInjection\Loader\LoaderInterface;

Categories