I have a structure representing a form and I want to iterate it using RecursiveIterator.
The problem is this only returns the top-level questions. What am I doing wrong?
Whole form:
class Form implements RecursiveIterator{
private $id;
private $caption;
private $other_text;
private $questions = array();
private $current;
private function __construct(DibiRow $row){
$this->id = $row->id;
$this->caption = $row->caption;
$this->other_text = $row->other_text;
$this->loadQuestions();
}
private function loadQuestions(){
$questions = dibi::query('SELECT * FROM cyp_questions WHERE form_id = %i AND parent_id IS NULL', $this->id);
while($question = $questions->fetch()) $this->questions[] = new Question($question->question_id, $question->type, $question->caption, $question->other_text, $question->triggers_unique == 1);
}
/**
* #throws InvalidArgumentException
* #param $id
* #return Form
*/
public static function loadById($id){
$form = dibi::query('SELECT * FROM cyp_forms WHERE id = %i', $id)->fetch();
if($form === false) throw new InvalidArgumentException('Form with id '.$id.' was not found.');
return new Form($form);
}
/**
* #throws FormFieldException
* #return bool
*/
public function validate($postfields){
}
public function getQuestions(){
return $this->questions;
}
public function getChildren(){
return $this->questions[$this->current];
}
public function hasChildren(){
return count($this->questions) > 0;
}
public function current(){
return $this->questions[$this->current];
}
public function key(){
return $this->current;
}
public function next(){
$this->current++;
}
public function rewind(){
$this->current = 0;
}
public function valid(){
return isset($this->questions[$this->current]);
}
}
Question:
class Question implements RecursiveIterator{
private $id;
private $type;
private $answers = array();
private $subquestions = array();
private $other_text;
private $triggers_unique;
private $caption;
private $current = 0;
public function __construct($id, $type, $caption, $other_text = null, $triggers_unique = false){
$this->id = $id;
$this->type = $type;
$this->caption = $caption;
$this->other_text = $other_text;
$this->triggers_unique = $triggers_unique;
$this->setSubQuestions();
}
private function setSubQuestions(){
$questions = dibi::query('SELECT * FROM cyp_questions WHERE parent_id = %i', $this->id);
while($question = $questions->fetch()) $this->subquestions[] = new Question($question->question_id, $question->type, $question->caption, $question->other_text, $question->triggers_unique == 1);
}
public function getOtherText(){
return $this->other_text;
}
public function getCaption(){
return $this->caption;
}
public function addAnswer($answer){
$this->answers[] = $answer;
}
public function getChildren(){
return $this->subquestions[$this->current];
}
public function hasChildren(){
return count($this->subquestions) > 0;
}
public function current(){
return $this->subquestions[$this->current];
}
public function key(){
return $this->id;
}
public function next(){
++$this->current;
}
public function rewind(){
$this->current = 0;
}
public function valid(){
return isset($this->subquestions[$this->current]);
}
public function getAnswers(){
return $this->answers;
}
}
Iteration:
$form = Form::loadById(1);
foreach($form as $question){
echo $question->getCaption().'<br />';
}
To iterate over a RecursiveIterator, you have to wrap it into a RecursiveIteratorIterator.
See some examples at
Introduction to Spl
SplWiki
The default iteration mode is only to list leaves. If you also want the containing nodes to appear in the iteration, pass RecursiveIteratorIterator::SELF_FIRST as the second argument to the constructor of the RecursiveIteratorIterator
Well, as you can see here
public RecursiveIterator RecursiveIterator::getChildren ( void )
Returns an iterator for the current iterator entry.
the method should return an object implementing the iterator. Your method return a simple array.
My guess would be to return something like:
public function getChildren(){
return new Question($this->subquestions);
}
This is because you're using a RECURSIVE iterator so it's expected to have each node of the tree of the same type (an iterator)
Related
My entity :
class User{
id : int
name : string
boss : User()
}
I want to create a function that return an array() of users that work under a giving user.
example :
public function MyEmployers( User $user , array $usersList )
{
$myEmployers = array();
...
return $myEmployers;
}
$results = $this->myEmployers ( $employer1 , $allEmployers)
dump ( $results );
$results = [ 4 , 5 , 6 ];
I found a solution if someone can improve it feel free :
public $tree = array();
public function MyEmployers(User $user)
{
$superior_key_id = array();
$all_users = $this->getallusers();
$id = $user->getId();
foreach ($all_users as $user) {
if ($user->getSuperior())
$superior_key_id[$user->getSuperior()->getId()][] = $user;
}
$this->getSubEmployee($this->getUser(), $superior_key_id);
return ($this->tree);
}
public function getSubEmployee($user, $superior_key_id)
{
if (isset($superior_key_id[$user->getId()])) {
foreach ($superior_key_id[$user->getId()] as $user) {
$this->tree[] = $user;
$this->getSubEmployee($user, $superior_key_id);
}
}
return $user;
}
this one will get all bosses if you're interested :
public function MyBosses(User $user)
{
$bosses = array();
while ($user->getSuperior()) {
array_push($bosses, $user->getSuperior());
$user = $user->getSuperior();
}
return $bosses;
}
You could set up a one-to-many relationship between boss and employee
So you're user class could look like:
class User{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string")
*/
private $name;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="employee")
*/
private $boss;
/**
* #ORM\OneToMany(targetEntity="App\Entity\User", mappedBy="boss")
*/
private $employees;
public function __construct()
{
$this->employees = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
/**
* #return Collection|employees[]
*/
public function getEmployees(): Collection
{
return $this->employees;
}
public function addEmployee(employee $employee): self
{
if (!$this->employees->contains($employee)) {
$this->employees[] = $employee;
}
return $this;
}
public function removeEmployee(employee $employee): self
{
if ($this->employees->contains($employee)) {
$this->employees->removeElement($employee);
}
return $this;
}
public function getBoss(): ?Usesr
{
return $this->boss;
}
public function setBoss(?User $boss): self
{
$this->boss = $boss;
return $this;
}
}
You would need to set up the database relationship with the symfony make:entity command.
To get all employeers under a user, you could do something like:
function getAllEmployeesUnder(User $user)
{
$allEmployees = [];
foreach ($user->getEmployees as $employee) {
$allEmployees[] = $employee;
$allEmployees = array_merge($allEmployees, $this->getAllEmployeesUnder($employee));
}
return $allEmployees;
}
A snapshot of Explorer class can be see below -
class Explorer
{
//....
public function getIterator()
{
//$iterator = new FileSearchIterator($this->baseDir, $this->pattern, $this->buildFlag());
if ($this->iterator) {
return $this->iterator;
}
$iterator = new RecursiveDirectoryIterator($this->baseDir, $this->buildFlag());
if ($this->ignoreVcsFiles) {
$this->ignore = array_merge($this->ignore, static::$vcsFiles);
}
if (!empty($this->ignore)) {
$iterator = new ExcludeFilter($iterator, $this->ignore);
}
if ($this->searchFor === static::SEARCH_FILES) {
$iterator = new FilenameRegexFilter($iterator, $this->pattern);
} else {
$iterator = new DirectoryRegexFilter($iterator, $this->pattern);
}
$this->iterator = new RecursiveIteratorIterator($iterator);
return $this->iterator;
}
//......
}
In Tests the given directory contains a single php file. But when filtering for only ****.php*** files using new FilenameRegexFilter(...) and then passing it through RecursiveIteratorIterator results in an empty RecursiveIteratorIterator instance.
You can see the rest of the filter classes (used above) below -
class ExcludeFilter extends \RecursiveFilterIterator
{
protected $iterator;
protected $ignore = [];
/**
* #inheritDoc
*/
public function __construct(\RecursiveIterator $iterator, array $ignore)
{
$this->iterator = $iterator;
$this->ignore = $ignore;
parent::__construct($iterator);
}
public function accept()
{
return !in_array($this->current()->getFilename(), $this->ignore, true);
}
public function getChildren()
{
$children = parent::getChildren();
$children->ignore = $this->ignore;
return $children;
}
}
class FilenameRegexFilter extends RecursiveRegexFilter
{
/**
* #inheritdoc
*/
public function accept()
{
return ($this->current()->isFile() && preg_match($this->regex, $this->current()->getFilename()));
}
/**
* #return \RecursiveRegexIterator
*/
public function getChildren()
{
$children = parent::getChildren();
$children->regex = $this->regex;
return $children;
}
}
abstract class RecursiveRegexFilter extends \RecursiveRegexIterator
{
protected $regex;
protected $iterator;
/**
* RegexFilter constructor.
* #param \RecursiveIterator $iterator
* #param string $regex
*/
public function __construct(\RecursiveIterator $iterator, $regex)
{
$this->iterator = $iterator;
$this->regex = $this->toRegex($regex);
parent::__construct($iterator, $this->regex);
}
/**
* #return \RecursiveRegexIterator
*/
public function getChildren()
{
$children = new static($this->iterator->getChildren(), $this->regex);
return $children;
}
/**
* #param $pattern
* #param array $options
* #return string
*/
public function toRegex($pattern, $options = [])
{
$pattern = str_replace(array('\*', '\?'), array('.*','.'), preg_quote($pattern));
$pattern = '/^' . $pattern . '$/';
if (!empty($options)) {
$pattern .= implode('', $options);
}
return $pattern;
}
}
class DirectoryRegexFilter extends RecursiveRegexFilter
{
public function accept()
{
return ($this->current()->isDir() || preg_match($this->regex, $this->current()->getFilename()));
}
}
I don't get where I'm going wrong. Can someone please point me in the right direction.
EDIT: To simplify my Question largely is how do I use RecursiveDirectoryIterator with RecursiveFilterIterator
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();
}
I am trying to implement a simple menu composite pattern.
These are the following classes i came up with.
MenuItem:
namespace MYNAME\MYBUNDLE\Entity;
use MYNAME\MYBUNDLE\Menu\MenuComponent;
class MenuItem implements MenuComponent
{
private $id;
private $name;
private $path;
private $parent;
private $visible;
private $createdOn;
private $templating;
private $attr;
private $children;
private $website;
private $position = 1;
public function __construct($name = null, $path = null, $attr = array(), $visible = true)
{
$this->name = $name;
$this->path = $path;
$this->visible = $visible;
$this->attr = $attr;
$this->createdOn = new \DateTime;
}
public function prePersist()
{
$this->createdOn = new \DateTime;
}
public function build()
{
$data['menu_item'] = $this;
$data['options'] = $this->attr;
if($this->hasChildren())
return $this->templating->render('MYBUNDLE:Menu:menu_dropdown.html.twig', $data);
if($this->isChild())
return $this->parent->getTemplating()->render('MYBUNDLE:Menu:menu_item.html.twig', $data);
return $this->templating->render('MYBUNDLE:Menu:menu_item.html.twig', $data);
}
public function __toString()
{
return $this->name;
}
public function setTemplating($templating)
{
$this->templating = $templating;
}
/**
* #return bool
*/
public function isChild()
{
return $this->hasParent();
}
/**
* #return bool
*/
public function hasParent()
{
return isset($this->parent);
}
/**
* #return bool
*/
public function hasChildren()
{
return count($this->children) > 0;
}
}
If left out the getters and setters to make it a bit shorter here.
As you can see this is the entity and it contains a build() function, however this function uses the render method which in my opinion shouldn't be in an entity.
MenuController
<?php
namespace MYNAME\MYBUNDLE\Controller;
use MYNAME\MYBUNDLE\Menu\Menu;
use MYNAME\MYBUNDLE\Entity\MenuItem;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
class MenuController extends Controller
{
public function generateAction()
{
$menu = new Menu($this->get('templating'));
// load menu items
$items = $this->getDoctrine()->getRepository('MYBUNDLE:MenuItem')->findOrdered();
foreach($items as $item)
{
if(!$item->hasParent())
$menu->add($item);
}
return new Response($menu->build());
}
}
The MenuController gets called to render the menu:
{{ render(controller('MYBUNDLE:Menu:generate')) }}
I would also like this to be different since it doesn't look right. Perhaps it's better to create a twig function to render the menu?
MenuComponent:
namespace MYNAME\MYBUNDLE\Menu;
interface MenuComponent {
public function build();
}
Menu:
namespace MYNAME\MYBUNDLE\Menu;
class Menu implements MenuComponent
{
private $children;
private $templating;
public function __construct($templating)
{
$this->templating = $templating;
}
public function add(MenuComponent $component)
{
$component->setTemplating($this->templating);
$this->children[] = $component;
}
public function build()
{
return $this->templating->render('MYBUNDLE:Menu:menu.html.twig', array("menu_items" => $this->children));
}
}
Menu Contains the MenuComponents and will render the menu first, in each MenuItem it's build() method is called.
I think it's better to remove the rendering logic from my MenuItem entity and place this somewhere else, however i can't figure out on how to do this properly within this design pattern.
Any help or suggestion is appreciated.
i want to store Student Object to array. and i try to do with below code. but it always show array count as 0
class Student
{
$StudID = 0;
$Name = null;
}
class Students
{
static private $StudentData = array();
static public function AddNewStudent($id,$name)
{
echo("AuctionID :".$AuctionID."<br/>");
try{
$objstd = new Student();
$objstd->StuID = $id;
$objstd->Name = &name;
array_push($StudentData, $objstd);
}
catch (Exception $e)
{
echo("Error".$e->getMessage());
}
}
static public function TotalStudent()
{
return count($StudentData);
}
}
Students::AddNewStudent(1,"name");
Students::AddNewStudent(2,"name2");
Students::AddNewStudent(3,"name3");
echo('Total auction running : '.Students::TotalStudent().'<br/>');
when i try to show array count it shows 0. i want to store all student data in static list
or then after when ever i want to see the list i get the list from static class only...
Because you're creating a new array instead of referencing the one you declared. Use the self keyword to reference your static object property:
class Students
{
static private $StudentData = array();
static public function AddNewStudent($id,$name)
{
echo("AuctionID :".$AuctionID."<br/>");
try{
$objstd = new Student();
$objstd->StuID = $id;
$objstd->Name = &name;
array_push(self::$StudentData, $objstd);
}
catch (Exception $e)
{
echo("Error".$e->getMessage());
}
}
static public function TotalStudent()
{
return count(self::$StudentData);
}
}
In php you have to prefix static variables with self::, like this:
array_push(self::$StudentData, $objstd);
// and in count:
return count(self::$StudentData);
Why that complicated? Your Student class should take care of it's own, same for Students. Example:
$students = new Students();
$students[] = new Student(1, "name");
$students[] = new Student(2, "name2");
$students[] = new Student(3, "name3");
printf('Total auction running : %d.', count($students));
Example output:
Total auction running : 3.
The classes:
class Student
{
/**
* #var int
*/
private $id;
/**
* #var string
*/
private $name;
/**
* #param int $id
* #param string $name
*/
public function __construct($id, $name) {
$this->id = $id;
$this->name = $name;
}
/**
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* #return int
*/
public function getId()
{
return $this->id;
}
}
class Students extends ArrayObject
{
public function __construct()
{
parent::__construct(array());
}
public function offsetSet($index, $newval) {
if (!($newval instanceof Student)) {
throw new InvalidArgumentException('You can only add values of type Student.');
}
parent::offsetSet($index, $newval);
}
}