sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
private function step2a() { // if found, delete if preceded by u // (Note that the preceding u need not be in RV.) if ( ($position = $this->searchIfInRv(array( 'yamos', 'yendo', 'yeron', 'yan', 'yen', 'yais', 'yas', 'yes', 'yo', 'yó', 'ya', 'ye'))) != false) { $before = Utf8::substr($this->word, ($position-1), 1); if ( (isset($before)) && ($before == 'u') ) { $this->word = Utf8::substr($this->word, 0, $position); return true; } } return false; }
Step 2a: Verb suffixes beginning y
entailment
private function step2b() { // delete if ( ($position = $this->searchIfInRv(array( 'iésemos', 'iéramos', 'ábamos', 'iríamos', 'eríamos', 'aríamos', 'áramos', 'ásemos', 'eríais', 'aremos', 'eremos', 'iremos', 'asteis', 'ieseis', 'ierais', 'isteis', 'aríais', 'irían', 'aréis', 'erían', 'erías', 'eréis', 'iréis', 'irías', 'ieran', 'iesen', 'ieron', 'iendo', 'ieras', 'iríais', 'arían', 'arías', 'amos', 'imos', 'ados', 'idos', 'irán', 'irás', 'erán', 'erás', 'ería', 'iría', 'íais', 'arán', 'arás', 'aría', 'iera', 'iese', 'aste', 'iste', 'aban', 'aran', 'asen', 'aron', 'ando', 'abas', 'adas', 'idas', 'ases', 'aras', 'aré', 'erá', 'eré', 'áis', 'ías', 'irá', 'iré', 'aba', 'ían', 'ada', 'ara', 'ase', 'ida', 'ado', 'ido', 'ará', 'ad', 'ed', 'id', 'ís', 'ió', 'ar', 'er', 'ir', 'as', 'ía', 'an' ))) != false) { $this->word = Utf8::substr($this->word, 0, $position); return true; } // en es éis emos // delete, and if preceded by gu delete the u (the gu need not be in RV) if ( ($position = $this->searchIfInRv(array('éis', 'emos', 'en', 'es'))) != false) { $this->word = Utf8::substr($this->word, 0, $position); if ( ($position2 = $this->search(array('gu'))) != false) { $this->word = Utf8::substr($this->word, 0, ($position2+1)); } return true; } }
Step 2b: Other verb suffixes Search for the longest among the following suffixes in RV, and perform the action indicated.
entailment
private function step3() { // os a o á í ó // delete if in RV if ( ($position = $this->searchIfInRv(array('os', 'a', 'o', 'á', 'í', 'ó'))) != false) { $this->word = Utf8::substr($this->word, 0, $position); return true; } // e é // delete if in RV, and if preceded by gu with the u in RV delete the u if ( ($position = $this->searchIfInRv(array('e', 'é'))) != false) { $this->word = Utf8::substr($this->word, 0, $position); if ( ($position2 = $this->searchIfInRv(array('u'))) != false) { $before = Utf8::substr($this->word, ($position2-1), 1); if ( (isset($before)) && ($before == 'g') ) { $this->word = Utf8::substr($this->word, 0, $position2); return true; } } } return false; }
Step 3: residual suffix Search for the longest among the following suffixes in RV, and perform the action indicated.
entailment
private function finish() { $this->word = Utf8::str_replace(array('á', 'í', 'ó', 'é', 'ú'), array('a', 'i', 'o', 'e', 'u'), $this->word); }
And finally: Remove acute accents
entailment
public function stem($word) { // we do ALL in UTF-8 if (! Utf8::check($word)) { throw new \Exception('Word must be in UTF-8'); } $this->word = Utf8::strtolower($word); $this->word = Utf8::str_replace(array('ã', 'õ'), array('a~', 'o~'), $this->word); $this->rv(); $this->r1(); $this->r2(); $word = $this->word; $this->step1(); if ($word == $this->word) { $this->step2(); } if ($word != $this->word) { $this->step3(); } else { $this->step4(); } $this->step5(); $this->finish(); return $this->word; }
{@inheritdoc}
entailment
public function step1() { // delete if in R2 if ( ($position = $this->search(array( 'amentos', 'imentos', 'adoras', 'adores', 'amento', 'imento', 'adora', 'istas', 'ismos', 'antes', 'ância', 'ezas', 'eza', 'icos', 'icas', 'ismo', 'ável', 'ível', 'ista', 'oso', 'osos', 'osas', 'osa', 'ico', 'ica', 'ador', 'aça~o', 'aço~es' , 'ante'))) !== false) { if ($this->inR2($position)) { $this->word = Utf8::substr($this->word, 0, $position); } return true; } // logía logías // replace with log if in R2 if ( ($position = $this->search(array('logías', 'logía'))) !== false) { if ($this->inR2($position)) { $this->word = preg_replace('#(logías|logía)$#u', 'log', $this->word); } return true; } // ución uciones // replace with u if in R2 if ( ($position = $this->search(array('uciones', 'ución'))) !== false) { if ($this->inR2($position)) { $this->word = preg_replace('#(uciones|ución)$#u', 'u', $this->word); } return true; } // ência ências // replace with ente if in R2 if ( ($position = $this->search(array('ências', 'ência'))) !== false) { if ($this->inR2($position)) { $this->word = preg_replace('#(ências|ência)$#u', 'ente', $this->word); } return true; } // amente // delete if in R1 // if preceded by iv, delete if in R2 (and if further preceded by at, delete if in R2), otherwise, // if preceded by os, ic or ad, delete if in R2 if ( ($position = $this->search(array('amente'))) !== false) { // delete if in R1 if ($this->inR1($position)) { $this->word = Utf8::substr($this->word, 0, $position); } // if preceded by iv, delete if in R2 (and if further preceded by at, delete if in R2), otherwise, if ( ($position2 = $this->searchIfInR2(array('iv'))) !== false) { $this->word = Utf8::substr($this->word, 0, $position2); if ( ($position3 = $this->searchIfInR2(array('at'))) !== false) { $this->word = Utf8::substr($this->word, 0, $position3); } // if preceded by os, ic or ad, delete if in R2 } elseif ( ($position4 = $this->searchIfInR2(array('os', 'ic', 'ad'))) !== false) { $this->word = Utf8::substr($this->word, 0, $position4); } return true; } // mente // delete if in R2 // if preceded by ante, avel or ível, delete if in R2 if ( ($position = $this->search(array('mente'))) !== false) { // delete if in R2 if ($this->inR2($position)) { $this->word = Utf8::substr($this->word, 0, $position); } // if preceded by ante, avel or ível, delete if in R2 if ( ($position2 = $this->searchIfInR2(array('ante', 'avel', 'ível'))) != false) { $this->word = Utf8::substr($this->word, 0, $position2); } return true; } // idade idades // delete if in R2 // if preceded by abil, ic or iv, delete if in R2 if ( ($position = $this->search(array('idades', 'idade'))) !== false) { // delete if in R2 if ($this->inR2($position)) { $this->word = Utf8::substr($this->word, 0, $position); } // if preceded by abil, ic or iv, delete if in R2 if ( ($position2 = $this->searchIfInR2(array('abil', 'ic', 'iv'))) !== false) { $this->word = Utf8::substr($this->word, 0, $position2); } return true; } // iva ivo ivas ivos // delete if in R2 // if preceded by at, delete if in R2 if ( ($position = $this->search(array('ivas', 'ivos', 'iva', 'ivo'))) !== false) { // delete if in R2 if ($this->inR2($position)) { $this->word = Utf8::substr($this->word, 0, $position); } // if preceded by at, delete if in R2 if ( ($position2 = $this->searchIfInR2(array('at'))) !== false) { $this->word = Utf8::substr($this->word, 0, $position2); } return true; } // ira iras // replace with ir if in RV and preceded by e if ( ($position = $this->search(array('iras', 'ira'))) !== false) { if ($this->inRv($position)) { $before = $position -1; $letter = Utf8::substr($this->word, $before, 1); if ($letter == 'e') { $this->word = preg_replace('#(iras|ira)$#u', 'ir', $this->word); } } return true; } return false; }
Step 1: Standard suffix removal
entailment
public function step2() { if ( ($position = $this->searchIfInRv(array( 'aríamos', 'eríamos', 'iríamos', 'ássemos', 'êssemos', 'íssemos', 'aríeis', 'eríeis', 'iríeis', 'ásseis', 'ésseis', 'ísseis', 'áramos', 'éramos', 'íramos', 'ávamos', 'aremos', 'eremos', 'iremos', 'ariam', 'eriam', 'iriam', 'assem', 'essem', 'issem', 'arias', 'erias', 'irias', 'ardes', 'erdes', 'irdes', 'asses', 'esses', 'isses', 'astes', 'estes', 'istes', 'áreis', 'areis', 'éreis', 'ereis', 'íreis', 'ireis', 'áveis', 'íamos', 'armos', 'ermos', 'irmos', 'aria', 'eria', 'iria', 'asse', 'esse', 'isse', 'aste', 'este', 'iste', 'arei', 'erei', 'irei', 'adas', 'idas', 'aram', 'eram', 'iram', 'avam', 'arem', 'erem', 'irem', 'ando', 'endo', 'indo', 'ara~o', 'era~o', 'ira~o', 'arás', 'aras', 'erás', 'eras', 'irás', 'avas', 'ares', 'eres', 'ires', 'íeis', 'ados', 'idos', 'ámos', 'amos', 'emos', 'imos', 'iras', 'ada', 'ida', 'ará', 'ara', 'erá', 'era', 'irá', 'ava', 'iam', 'ado', 'ido', 'ias', 'ais', 'eis', 'ira', 'ia', 'ei', 'am', 'em', 'ar', 'er', 'ir', 'as', 'es', 'is', 'eu', 'iu', 'ou', ))) !== false) { $this->word = Utf8::substr($this->word, 0, $position); return true; } return false; }
Step 2: Verb suffixes Search for the longest among the following suffixes in RV, and if found, delete.
entailment
public function step3() { // Delete suffix i if in RV and preceded by c if ($this->searchIfInRv(array('i')) !== false) { $letter = Utf8::substr($this->word, -2, 1); if ($letter == 'c') { $this->word = Utf8::substr($this->word, 0, -1); } return true; } return false; }
Step 3: d-suffixes
entailment
public function step4() { // If the word ends with one of the suffixes "os a i o á í ó" in RV, delete it if ( ($position = $this->searchIfInRv(array('os', 'a', 'i', 'o','á', 'í', 'ó'))) !== false) { $this->word = Utf8::substr($this->word, 0, $position); return true; } return false; }
Step 4
entailment
public function step5() { // If the word ends with one of "e é ê" in RV, delete it, and if preceded by gu (or ci) with the u (or i) in RV, delete the u (or i). if ($this->searchIfInRv(array('e', 'é', 'ê')) !== false) { $this->word = Utf8::substr($this->word, 0, -1); if ( ($position2 = $this->search(array('gu', 'ci'))) !== false) { if ($this->inRv(($position2+1))) { $this->word = Utf8::substr($this->word, 0, -1); } } return true; } else if ($this->search(array('ç')) !== false) { $this->word = preg_replace('#(ç)$#u', 'c', $this->word); return true; } return false; }
Step 5
entailment
public function stem($word) { // we do ALL in UTF-8 if (! Utf8::check($word)) { throw new \Exception('Word must be in UTF-8'); } $this->word = Utf8::strtolower($word); // R2 is not used: R1 is defined in the same way as in the German stemmer $this->r1(); // then R1 is adjusted so that the region before it contains at least 3 letters. if ($this->r1Index < 3) { $this->r1Index = 3; $this->r1 = Utf8::substr($this->word, 3); } // Do each of steps 1, 2 3 and 4. $this->step1(); $this->step2(); $this->step3(); return $this->word; }
{@inheritdoc}
entailment
private function step2() { // dd gd nn dt gt kt tt if ($this->searchIfInR1(array('dd', 'gd', 'nn', 'dt', 'gt', 'kt', 'tt')) !== false) { $this->word = Utf8::substr($this->word, 0, -1); } }
Step 2 Search for one of the following suffixes in R1, and if found delete the last letter.
entailment
private function step3() { // lig ig els // delete if ( ($position = $this->searchIfInR1(array('lig', 'ig', 'els'))) !== false) { $this->word = Utf8::substr($this->word, 0, $position); return true; } // löst // replace with lös if ( ($this->searchIfInR1(array('löst'))) !== false) { $this->word = Utf8::substr($this->word, 0, -1); return true; } // fullt // replace with full if ( ($this->searchIfInR1(array('fullt'))) !== false) { $this->word = Utf8::substr($this->word, 0, -1); return true; } }
Step 3: Search for the longest among the following suffixes in R1, and perform the action indicated.
entailment
public function stem($word) { // we do ALL in UTF-8 if (! Utf8::check($word)) { throw new \Exception('Word must be in UTF-8'); } $this->word = Utf8::strtolower($word); $this->plainVowels = implode('', self::$vowels); $this->step0(); $this->rv(); $this->r1(); $this->r2(); // to know if step1, 2a or 2b have altered the word $this->originalWord = $this->word; $nextStep = $this->step1(); // Do step 2a if either no ending was removed by step 1, or if one of endings amment, emment, ment, ments was found. if ( ($nextStep == 2) || ($this->originalWord == $this->word) ) { $modified = $this->step2a(); if (!$modified) { $this->step2b(); } } if ($this->word != $this->originalWord) { $this->step3(); } else { $this->step4(); } $this->step5(); $this->step6(); $this->finish(); return $this->word; }
{@inheritdoc}
entailment
private function step0() { $this->word = preg_replace('#([q])u#u', '$1U', $this->word); $this->word = preg_replace('#(['.$this->plainVowels.'])y#u', '$1Y', $this->word); $this->word = preg_replace('#y(['.$this->plainVowels.'])#u', 'Y$1', $this->word); $this->word = preg_replace('#(['.$this->plainVowels.'])u(['.$this->plainVowels.'])#u', '$1U$2', $this->word); $this->word = preg_replace('#(['.$this->plainVowels.'])i(['.$this->plainVowels.'])#u', '$1I$2', $this->word); }
Assume the word is in lower case. Then put into upper case u or i preceded and followed by a vowel, and y preceded or followed by a vowel. u after q is also put into upper case. For example, jouer -> joUer ennuie -> ennuIe yeux -> Yeux quand -> qUand
entailment
private function step1() { // ance iqUe isme able iste eux ances iqUes ismes ables istes // delete if in R2 if ( ($position = $this->search(array('ances', 'iqUes', 'ismes', 'ables', 'istes', 'ance', 'iqUe','isme', 'able', 'iste', 'eux'))) !== false) { if ($this->inR2($position)) { $this->word = Utf8::substr($this->word, 0, $position); } return 3; } // atrice ateur ation atrices ateurs ations // delete if in R2 // if preceded by ic, delete if in R2, else replace by iqU if ( ($position = $this->search(array('atrices', 'ateurs', 'ations', 'atrice', 'ateur', 'ation'))) !== false) { if ($this->inR2($position)) { $this->word = Utf8::substr($this->word, 0, $position); if ( ($position2 = $this->searchIfInR2(array('ic'))) !== false) { $this->word = Utf8::substr($this->word, 0, $position2); } else { $this->word = preg_replace('#(ic)$#u', 'iqU', $this->word); } } return 3; } // logie logies // replace with log if in R2 if ( ($position = $this->search(array('logies', 'logie'))) !== false) { if ($this->inR2($position)) { $this->word = preg_replace('#(logies|logie)$#u', 'log', $this->word); } return 3; } // usion ution usions utions // replace with u if in R2 if ( ($position = $this->search(array('usions', 'utions', 'usion', 'ution'))) !== false) { if ($this->inR2($position)) { $this->word = preg_replace('#(usion|ution|usions|utions)$#u', 'u', $this->word); } return 3; } // ence ences // replace with ent if in R2 if ( ($position = $this->search(array('ences', 'ence'))) !== false) { if ($this->inR2($position)) { $this->word = preg_replace('#(ence|ences)$#u', 'ent', $this->word); } return 3; } // issement issements // delete if in R1 and preceded by a non-vowel if ( ($position = $this->search(array('issements', 'issement'))) != false) { if ($this->inR1($position)) { $before = $position - 1; $letter = Utf8::substr($this->word, $before, 1); if (! in_array($letter, self::$vowels)) { $this->word = Utf8::substr($this->word, 0, $position); } } return 3; } // ement ements // delete if in RV // if preceded by iv, delete if in R2 (and if further preceded by at, delete if in R2), otherwise, // if preceded by eus, delete if in R2, else replace by eux if in R1, otherwise, // if preceded by abl or iqU, delete if in R2, otherwise, // if preceded by ièr or Ièr, replace by i if in RV if ( ($position = $this->search(array('ements', 'ement'))) !== false) { // delete if in RV if ($this->inRv($position)) { $this->word = Utf8::substr($this->word, 0, $position); } // if preceded by iv, delete if in R2 (and if further preceded by at, delete if in R2), otherwise, if ( ($position = $this->searchIfInR2(array('iv'))) !== false) { $this->word = Utf8::substr($this->word, 0, $position); if ( ($position2 = $this->searchIfInR2(array('at'))) !== false) { $this->word = Utf8::substr($this->word, 0, $position2); } // if preceded by eus, delete if in R2, else replace by eux if in R1, otherwise, } elseif ( ($position = $this->search(array('eus'))) !== false) { if ($this->inR2($position)) { $this->word = Utf8::substr($this->word, 0, $position); } elseif ($this->inR1($position)) { $this->word = preg_replace('#(eus)$#u', 'eux', $this->word); } // if preceded by abl or iqU, delete if in R2, otherwise, } elseif ( ($position = $this->searchIfInR2(array('abl', 'iqU'))) !== false) { $this->word = Utf8::substr($this->word, 0, $position); // if preceded by ièr or Ièr, replace by i if in RV } elseif ( ($position = $this->searchIfInRv(array('ièr', 'Ièr'))) !== false) { $this->word = preg_replace('#(ièr|Ièr)$#u', 'i', $this->word); } return 3; } // ité ités // delete if in R2 // if preceded by abil, delete if in R2, else replace by abl, otherwise, // if preceded by ic, delete if in R2, else replace by iqU, otherwise, // if preceded by iv, delete if in R2 if ( ($position = $this->search(array('ités', 'ité'))) !== false) { // delete if in R2 if ($this->inR2($position)) { $this->word = Utf8::substr($this->word, 0, $position); } // if preceded by abil, delete if in R2, else replace by abl, otherwise, if ( ($position = $this->search(array('abil'))) !== false) { if ($this->inR2($position)) { $this->word = Utf8::substr($this->word, 0, $position); } else { $this->word = preg_replace('#(abil)$#u', 'abl', $this->word); } // if preceded by ic, delete if in R2, else replace by iqU, otherwise, } elseif ( ($position = $this->search(array('ic'))) !== false) { if ($this->inR2($position)) { $this->word = Utf8::substr($this->word, 0, $position); } else { $this->word = preg_replace('#(ic)$#u', 'iqU', $this->word); } // if preceded by iv, delete if in R2 } elseif ( ($position = $this->searchIfInR2(array('iv'))) !== false) { $this->word = Utf8::substr($this->word, 0, $position); } return 3; } // if ive ifs ives // delete if in R2 // if preceded by at, delete if in R2 (and if further preceded by ic, delete if in R2, else replace by iqU) if ( ($position = $this->search(array('ifs', 'ives', 'if', 'ive'))) !== false) { if ($this->inR2($position)) { $this->word = Utf8::substr($this->word, 0, $position); } if ( ($position = $this->searchIfInR2(array('at'))) !== false) { $this->word = Utf8::substr($this->word, 0, $position); if ( ($position2 = $this->search(array('ic'))) !== false) { if ($this->inR2($position2)) { $this->word = Utf8::substr($this->word, 0, $position2); } else { $this->word = preg_replace('#(ic)$#u', 'iqU', $this->word); } } } return 3; } // eaux // replace with eau if ( ($position = $this->search(array('eaux'))) !== false) { $this->word = preg_replace('#(eaux)$#u', 'eau', $this->word); return 3; } // aux // replace with al if in R1 if ( ($position = $this->search(array('aux'))) !== false) { if ($this->inR1($position)) { $this->word = preg_replace('#(aux)$#u', 'al', $this->word); } return 3; } // euse euses // delete if in R2, else replace by eux if in R1 if ( ($position = $this->search(array('euses', 'euse'))) !== false) { if ($this->inR2($position)) { $this->word = Utf8::substr($this->word, 0, $position); } elseif ($this->inR1($position)) { $this->word = preg_replace('#(euses|euse)$#u', 'eux', $this->word); //return 3; } return 3; } // amment // replace with ant if in RV if ( ($position = $this->search(array('amment'))) !== false) { if ($this->inRv($position)) { $this->word = preg_replace('#(amment)$#u', 'ant', $this->word); } return 2; } // emment // replace with ent if in RV if ( ($position = $this->search(array('emment'))) !== false) { if ($this->inRv($position)) { $this->word = preg_replace('#(emment)$#u', 'ent', $this->word); } return 2; } // ment ments // delete if preceded by a vowel in RV if ( ($position = $this->search(array('ments', 'ment'))) != false) { $before = $position - 1; $letter = Utf8::substr($this->word, $before, 1); if ( $this->inRv($before) && (in_array($letter, self::$vowels)) ) { $this->word = Utf8::substr($this->word, 0, $position); } return 2; } return 2; }
Step 1 Search for the longest among the following suffixes, and perform the action indicated. @return integer Next step number
entailment
private function step2a() { if ( ($position = $this->searchIfInRv(array( 'îmes', 'îtes', 'ît', 'ies', 'ie', 'iraIent', 'irais', 'irait', 'irai', 'iras', 'ira', 'irent', 'irez', 'iriez', 'irions', 'irons', 'iront', 'ir', 'issaIent', 'issais', 'issait', 'issant', 'issantes', 'issante', 'issants', 'issent', 'isses', 'issez', 'isse', 'issiez', 'issions', 'issons', 'is', 'it', 'i'))) !== false) { $before = $position - 1; $letter = Utf8::substr($this->word, $before, 1); if ( $this->inRv($before) && (!in_array($letter, self::$vowels)) ) { $this->word = Utf8::substr($this->word, 0, $position); return true; } } return false; }
Step 2a: Verb suffixes beginning i In steps 2a and 2b all tests are confined to the RV region. Search for the longest among the following suffixes and if found, delete if preceded by a non-vowel. îmes ît îtes i ie ies ir ira irai iraIent irais irait iras irent irez iriez irions irons iront is issaIent issais issait issant issante issantes issants isse issent isses issez issiez issions issons it (Note that the non-vowel itself must also be in RV.)
entailment
private function step2b() { // é ée ées és èrent er era erai eraIent erais erait eras erez eriez erions erons eront ez iez // delete if ( ($position = $this->searchIfInRv(array( 'ées', 'èrent', 'erais', 'erait', 'erai', 'eraIent', 'eras', 'erez', 'eriez', 'erions', 'erons', 'eront', 'era', 'er', 'iez', 'ez','és', 'ée', 'é'))) !== false) { $this->word = Utf8::substr($this->word, 0, $position); return true; } // âmes ât âtes a ai aIent ais ait ant ante antes ants as asse assent asses assiez assions // delete // if preceded by e, delete if ( ($position = $this->searchIfInRv(array( 'âmes', 'âtes', 'ât', 'aIent', 'ais', 'ait', 'antes', 'ante', 'ants', 'ant', 'assent', 'asses', 'assiez', 'assions', 'asse', 'as', 'ai', 'a'))) !== false) { $before = $position - 1; $letter = Utf8::substr($this->word, $before, 1); if ( $this->inRv($before) && ($letter == 'e') ) { $this->word = Utf8::substr($this->word, 0, $before); } else { $this->word = Utf8::substr($this->word, 0, $position); } return true; } // ions // delete if in R2 if ( ($position = $this->searchIfInRv(array('ions'))) !== false) { if ($this->inR2($position)) { $this->word = Utf8::substr($this->word, 0, $position); } return true; } return false; }
Do step 2b if step 2a was done, but failed to remove a suffix. Step 2b: Other verb suffixes
entailment
private function step3() { $this->word = preg_replace('#(Y)$#u', 'i', $this->word); $this->word = preg_replace('#(ç)$#u', 'c', $this->word); }
Step 3: Replace final Y with i or final ç with c
entailment
private function step4() { //If the word ends s, not preceded by a, i, o, u, è or s, delete it. if (preg_match('#[^aiouès]s$#', $this->word)) { $this->word = Utf8::substr($this->word, 0, -1); } // In the rest of step 4, all tests are confined to the RV region. // ion // delete if in R2 and preceded by s or t if ( (($position = $this->searchIfInRv(array('ion'))) !== false) && ($this->inR2($position)) ) { $before = $position - 1; $letter = Utf8::substr($this->word, $before, 1); if ( $this->inRv($before) && (($letter == 's') || ($letter == 't')) ) { $this->word = Utf8::substr($this->word, 0, $position); } return true; } // ier ière Ier Ière // replace with i if ( ($this->searchIfInRv(array('ier', 'ière', 'Ier', 'Ière'))) !== false) { $this->word = preg_replace('#(ier|ière|Ier|Ière)$#u', 'i', $this->word); return true; } // e // delete if ( ($this->searchIfInRv(array('e'))) !== false) { $this->word = Utf8::substr($this->word, 0, -1); return true; } // ë // if preceded by gu, delete if ( ($position = $this->searchIfInRv(array('guë'))) !== false) { if ($this->inRv($position+2)) { $this->word = Utf8::substr($this->word, 0, -1); return true; } } return false; }
Step 4: Residual suffix
entailment
private function step5() { if ($this->search(array('enn', 'onn', 'ett', 'ell', 'eill')) !== false) { $this->word = Utf8::substr($this->word, 0, -1); } }
Step 5: Undouble If the word ends enn, onn, ett, ell or eill, delete the last letter
entailment
private function step6() { $this->word = preg_replace('#(é|è)([^'.$this->plainVowels.']+)$#u', 'e$2', $this->word); }
Step 6: Un-accent If the words ends é or è followed by at least one non-vowel, remove the accent from the e.
entailment
protected function rv() { $length = Utf8::strlen($this->word); $this->rv = ''; $this->rvIndex = $length; if ($length < 3) { return true; } // If the word begins with two vowels, RV is the region after the third letter $first = Utf8::substr($this->word, 0, 1); $second = Utf8::substr($this->word, 1, 1); if ( (in_array($first, self::$vowels)) && (in_array($second, self::$vowels)) ) { $this->rv = Utf8::substr($this->word, 3); $this->rvIndex = 3; return true; } // (Exceptionally, par, col or tap, at the begining of a word is also taken to define RV as the region to their right.) $begin3 = Utf8::substr($this->word, 0, 3); if (in_array($begin3, array('par', 'col', 'tap'))) { $this->rv = Utf8::substr($this->word, 3); $this->rvIndex = 3; return true; } // otherwise the region after the first vowel not at the beginning of the word, for ($i=1; $i<$length; $i++) { $letter = Utf8::substr($this->word, $i, 1); if (in_array($letter, self::$vowels)) { $this->rv = Utf8::substr($this->word, ($i + 1)); $this->rvIndex = $i + 1; return true; } } return false; }
If the word begins with two vowels, RV is the region after the third letter, otherwise the region after the first vowel not at the beginning of the word, or the end of the word if these positions cannot be found. (Exceptionally, par, col or tap, at the begining of a word is also taken to define RV as the region to their right.)
entailment
private function hasValidSEnding($word) { $lastLetter = Utf8::substr($word, -1, 1); if (in_array($lastLetter, array('b', 'c', 'd', 'f', 'g', 'h', 'j', 'l', 'm', 'n', 'o', 'p', 'r', 't', 'v', 'y', 'z'))) { return true; } if ($lastLetter == 'k') { $beforeLetter = Utf8::substr($word, -2, 1); if (!in_array($beforeLetter, self::$vowels)) { return true; } } return false; }
Define a valid s-ending as one of b c d f g h j l m n o p r t v y z, or k not preceded by a vowel @param string $ending @return boolean
entailment
private function step1() { // erte ert // replace with er if ( ($position = $this->searchIfInR1(array('erte', 'ert'))) !== false) { $this->word = preg_replace('#(erte|ert)$#u', 'er', $this->word); return true; } // a e ede ande ende ane ene hetene en heten ar er heter as es edes endes enes hetenes ens hetens ers ets et het ast // delete if ( ($position = $this->searchIfInR1(array( 'hetenes', 'hetene', 'hetens', 'heten', 'endes', 'heter', 'ande', 'ende', 'enes', 'edes', 'ede', 'ane', 'ene', 'het', 'ers', 'ets', 'ast', 'ens', 'en', 'ar', 'er', 'as', 'es', 'et', 'a', 'e' ))) !== false) { $this->word = Utf8::substr($this->word, 0, $position); return true; } // s // delete if preceded by a valid s-ending if ( ($position = $this->searchIfInR1(array('s'))) !== false) { $word = Utf8::substr($this->word, 0, $position); if ($this->hasValidSEnding($word)) { $this->word = $word; } return true; } }
Step 1 Search for the longest among the following suffixes in R1, and perform the action indicated.
entailment
private function step3() { // leg eleg ig eig lig elig els lov elov slov hetslov if ( ($position = $this->searchIfInR1(array( 'hetslov', 'eleg', 'elov', 'slov', 'elig', 'eig', 'lig', 'els', 'lov', 'leg', 'ig' ))) !== false) { $this->word = Utf8::substr($this->word, 0, $position); } }
Step 3: Search for the longest among the following suffixes in R1, and if found, delete.
entailment
public function stem($word) { // we do ALL in UTF-8 if (! Utf8::check($word)) { throw new \Exception('Word must be in UTF-8'); } $this->word = Utf8::strtolower($word); // First, remove all umlaut and acute accents. $this->word = Utf8::str_replace( array('ä', 'ë', 'ï', 'ö', 'ü', 'á', 'é', 'í', 'ó', 'ú'), array('a', 'e', 'i', 'o', 'u', 'a', 'e', 'i', 'o', 'u'), $this->word); $this->plainVowels = implode('', self::$vowels); // Put initial y, y after a vowel, and i between vowels into upper case. $this->word = preg_replace('#^y#u', 'Y', $this->word); $this->word = preg_replace('#(['.$this->plainVowels.'])y#u', '$1Y', $this->word); $this->word = preg_replace('#(['.$this->plainVowels.'])i(['.$this->plainVowels.'])#u', '$1I$2', $this->word); // R1 and R2 (see the note on R1 and R2) are then defined as in German. // R1 and R2 are first set up in the standard way $this->r1(); $this->r2(); // but then R1 is adjusted so that the region before it contains at least 3 letters. if ($this->r1Index < 3) { $this->r1Index = 3; $this->r1 = Utf8::substr($this->word, 3); } // Do each of steps 1, 2 3 and 4. $this->step1(); $removedE = $this->step2(); $this->step3a(); $this->step3b($removedE); $this->step4(); $this->finish(); return $this->word; }
{@inheritdoc}
entailment
private function hasValidSEnding($word) { $lastLetter = Utf8::substr($word, -1, 1); return !in_array($lastLetter, array_merge(self::$vowels, array('j'))); }
Define a valid s-ending as a non-vowel other than j. @param string $ending @return boolean
entailment
private function hasValidEnEnding($word) { $lastLetter = Utf8::substr($word, -1, 1); if (in_array($lastLetter, self::$vowels)) { return false; } $threeLastLetters = Utf8::substr($word, -3, 3); if ($threeLastLetters == 'gem') { return false; } return true; }
Define a valid en-ending as a non-vowel, and not gem. @param string $ending @return boolean
entailment
private function unDoubling() { if ($this->search(array('kk', 'dd', 'tt')) !== false) { $this->word = Utf8::substr($this->word, 0, -1); } }
Define undoubling the ending as removing the last letter if the word ends kk, dd or tt.
entailment
private function step1() { // heden // replace with heid if in R1 if ( ($position = $this->search(array('heden'))) !== false) { if ($this->inR1($position)) { $this->word = preg_replace('#(heden)$#u', 'heid', $this->word); } return true; } // en ene // delete if in R1 and preceded by a valid en-ending, and then undouble the ending if ( ($position = $this->search(array('ene', 'en'))) !== false) { if ($this->inR1($position)) { $word = Utf8::substr($this->word, 0, $position); if ($this->hasValidEnEnding($word)) { $this->word = $word; $this->unDoubling(); } } return true; } // s se // delete if in R1 and preceded by a valid s-ending if ( ($position = $this->search(array('se', 's'))) !== false) { if ($this->inR1($position)) { $word = Utf8::substr($this->word, 0, $position); if ($this->hasValidSEnding($word)) { $this->word = $word; } } return true; } return false; }
Step 1 Search for the longest among the following suffixes, and perform the action indicated
entailment
private function step2() { if ( ($position = $this->search(array('e'))) !== false) { if ($this->inR1($position)) { $letter = Utf8::substr($this->word, -2, 1); if (!in_array($letter, self::$vowels)) { $this->word = Utf8::substr($this->word, 0, $position); $this->unDoubling(); return true; } } } return false; }
Step 2 Delete suffix e if in R1 and preceded by a non-vowel, and then undouble the ending
entailment
private function step3a() { if ( ($position = $this->search(array('heid'))) !== false) { if ($this->inR2($position)) { $letter = Utf8::substr($this->word, -5, 1); if ($letter !== 'c') { $this->word = Utf8::substr($this->word, 0, $position); if ( ($position = $this->search(array('en'))) !== false) { if ($this->inR1($position)) { $word = Utf8::substr($this->word, 0, $position); if ($this->hasValidEnEnding($word)) { $this->word = $word; $this->unDoubling(); } } } } } } }
Step 3a: heid delete heid if in R2 and not preceded by c, and treat a preceding en as in step 1(b)
entailment
private function step3b($removedE) { // end ing // delete if in R2 // if preceded by ig, delete if in R2 and not preceded by e, otherwise undouble the ending if ( ($position = $this->search(array('end', 'ing'))) !== false) { if ($this->inR2($position)) { $this->word = Utf8::substr($this->word, 0, $position); if ( ($position2 = $this->searchIfInR2(array('ig'))) !== false) { $letter = Utf8::substr($this->word, -3, 1); if ($letter !== 'e') { $this->word = Utf8::substr($this->word, 0, $position2); } } else { $this->unDoubling(); } } return true; } // ig // delete if in R2 and not preceded by e if ( ($position = $this->search(array('ig'))) !== false) { if ($this->inR2($position)) { $letter = Utf8::substr($this->word, -3, 1); if ($letter !== 'e') { $this->word = Utf8::substr($this->word, 0, $position); } } return true; } // lijk // delete if in R2, and then repeat step 2 if ( ($position = $this->search(array('lijk'))) !== false) { if ($this->inR2($position)) { $this->word = Utf8::substr($this->word, 0, $position); $this->step2(); } return true; } // baar // delete if in R2 if ( ($position = $this->search(array('baar'))) !== false) { if ($this->inR2($position)) { $this->word = Utf8::substr($this->word, 0, $position); } return true; } // bar // delete if in R2 and if step 2 actually removed an e if ( ($position = $this->search(array('bar'))) !== false) { if ($this->inR2($position) && $removedE) { $this->word = Utf8::substr($this->word, 0, $position); } return true; } return false; }
Step 3b: d-suffixe Search for the longest among the following suffixes, and perform the action indicated.
entailment
private function step4() { // D is a non-vowel other than I $d = Utf8::substr($this->word, -1, 1); if (in_array($d, array_merge(self::$vowels, array('I')))) { return false; } // V is double a, e, o or u $v = Utf8::substr($this->word, -3, 2); if (!in_array($v, array('aa', 'ee', 'oo', 'uu'))) { return false; } $singleV = Utf8::substr($v, 0, 1); // C is a non-vowel $c = Utf8::substr($this->word, -4, 1); if (in_array($c, self::$vowels)) { return false; } $this->word = Utf8::substr($this->word, 0, -4); $this->word .= $c . $singleV .$d; }
Step 4: undouble vowel If the words ends CVD, where C is a non-vowel, D is a non-vowel other than I, and V is double a, e, o or u, remove one of the vowels from V (for example, maan -> man, brood -> brod).
entailment
public function callback(array $callbacks) { if (isset($callbacks['before'])) { if (is_array($callbacks['before']) && !is_callable($callbacks['before'])) { foreach ($callbacks['before'] as $func) { if (is_callable($func)) { $this->callbacks['before'][] = $func; } else { self::exception($this, "The provided before callback function isn't callable", self::ERROR_CALLBACK); } } } else { if (is_callable($callbacks['before'])) { $this->callbacks['before'][] = $callbacks['before']; } else { self::exception($this, "The provided before callback function isn't callable", self::ERROR_CALLBACK); } } } if (isset($callbacks['after'])) { if (is_array($callbacks['after']) && !is_callable($callbacks['after'])) { foreach ($callbacks['after'] as $func) { if (is_callable($func)) { $this->callbacks['after'][] = $func; } else { self::exception($this, "The provided after callback function isn't callable", self::ERROR_CALLBACK); } } } else { if (is_callable($callbacks['after'])) { $this->callbacks['after'][] = $callbacks['after']; } else { self::exception($this, "The provided after callback function isn't callable", self::ERROR_CALLBACK); } } } return $this; }
Set callbacks for before and after filters. Callbacks are useful for example, if you have 2 or more AJAX functions, and you need to perform the same data manipulation, like removing an 'id' from the $_POST['args'], or to check for potential CSRF or SQL injection attempts on all the functions, clean data or perform START TRANSACTION for database, etc @param array $callbacks The callbacks <pre> array( // Set a function to be called BEFORE // processing the request, if it's an // AJAX to be processed request, can be // an array of callbacks 'before' => array|function, // Set a function to be called AFTER // processing the request, if it's an AJAX // processed request, can be an array of // callbacks 'after' => array|function ); </pre> The callback function should be <pre> // $additional_args is passed using the callback_data() function, // in this case, a before callback function before_callback($ajax_data, $internal_data){ // Do stuff $_POST['args']['id'] = $additional_args['id']; return true; } // after callback would be to save the data perhaps? Just to keep the code D.R.Y. function after_callback($ajax_data, $internal_data, $PheryResponse){ $this->database->save(); $PheryResponse->merge(PheryResponse::factory('#loading')->fadeOut()); return true; } </pre> Returning false on the callback will make the process() phase to RETURN, but won't exit. You may manually exit on the after callback if desired Any data that should be modified will be inside $_POST['args'] (can be accessed freely on 'before', will be passed to the AJAX function) @return Phery
entailment
protected static function exception($phery, $exception, $code) { if ($phery instanceof Phery && $phery->config['exceptions'] === true) { throw new PheryException($exception, $code); } return false; }
Throw an exception if enabled @param Phery $phery Instance @param string $exception @param integer $code @throws PheryException @return boolean
entailment
public function data($args) { foreach (func_get_args() as $arg) { if (is_array($arg)) { $this->data = array_merge_recursive($arg, $this->data); } else { $this->data[] = $arg; } } return $this; }
Set any data to pass to the callbacks @param mixed $args,... Parameters, can be anything @return Phery
entailment
public function csrf($check = false, $force = false) { if ($this->config['csrf'] !== true) { return !empty($check) ? true : ''; } if (session_id() == '' && $this->config['auto_session'] === true) { @session_start(); } if ($check === false) { $current_token = $this->get_csrf_token(); if (($current_token !== false && $force) || $current_token === false) { $token = sha1(uniqid(microtime(true), true)); $_SESSION['phery'] = array( 'csrf' => $token ); $token = base64_encode($token); } else { $token = base64_encode($_SESSION['phery']['csrf']); } return "<meta id=\"csrf-token\" name=\"csrf-token\" content=\"{$token}\" />\n"; } else { if (empty($_SESSION['phery']['csrf'])) { return false; } return $_SESSION['phery']['csrf'] === base64_decode($check, true); } }
Output the meta HTML with the token. This method needs to use sessions through session_start @param bool $check Check if the current token is valid @param bool $force It will renew the current hash every call @return string|bool
entailment
public static function is_ajax($is_phery = false) { switch ($is_phery) { case true: return (bool)(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strcasecmp($_SERVER['HTTP_X_REQUESTED_WITH'], 'XMLHttpRequest') === 0 && strtoupper($_SERVER['REQUEST_METHOD']) === 'POST' && !empty($_SERVER['HTTP_X_PHERY'])); case false: return (bool)(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strcasecmp($_SERVER['HTTP_X_REQUESTED_WITH'], 'XMLHttpRequest') === 0); } return false; }
Check if the current call is an ajax call @param bool $is_phery Check if is an ajax call and a phery specific call @static @return bool
entailment
private function stripslashes_recursive($variable) { if (!empty($variable) && is_string($variable)) { return stripslashes($variable); } if (!empty($variable) && is_array($variable)) { foreach ($variable as $i => $value) { $variable[$i] = $this->stripslashes_recursive($value); } } return $variable; }
Strip slashes recursive @param array|string $variable @return array|string
entailment
public static function error_handler($errno, $errstr, $errfile, $errline) { self::flush(true); $response = PheryResponse::factory()->exception($errstr, array( 'code' => $errno, 'file' => self::$expose_paths ? $errfile : pathinfo($errfile, PATHINFO_BASENAME), 'line' => $errline )); self::respond($response); self::shutdown_handler(false, true); }
Default error handler @param int $errno @param string $errstr @param string $errfile @param int $errline
entailment
public static function shutdown_handler($errors = false, $handled = false) { if ($handled) { self::flush(); } if ($errors === true && ($error = error_get_last()) && !$handled) { self::error_handler($error["type"], $error["message"], $error["file"], $error["line"]); } if (!$handled) { self::flush(); } if (session_id() != '') { session_write_close(); } exit; }
Default shutdown handler @param bool $errors @param bool $handled
entailment
public static function respond($response, $echo = true) { if ($response instanceof PheryResponse) { if (!headers_sent()) { if (session_id() != '') { session_write_close(); } header('Cache-Control: no-cache, must-revalidate', true); header('Expires: Sat, 26 Jul 1997 05:00:00 GMT', true); header('Content-Type: application/json; charset=' . (strtolower(self::$encoding)), true); header('Connection: close', true); } } if ($response) { $response = "{$response}"; } if ($echo === true) { echo $response; } return $response; }
Helper function to properly output the headers for a PheryResponse in case you need to manually return it (like when following a redirect) @param string|PheryResponse $response The response or a string @param bool $echo Echo the response @return string
entailment
public function views(array $views) { foreach ($views as $container => $callback) { if (is_callable($callback)) { $this->views[$container] = $callback; } } return $this; }
Set the callback for view portions, as defined in Phery.view() @param array $views Array consisting of array('#id_of_view' => callback) The callback is like a normal phery callback, but the second parameter receives different data. But it MUST always return a PheryResponse with render_view(). You can do any manipulation like you would in regular callbacks. If you want to manipulate the DOM AFTER it was rendered, do it javascript side, using the afterHtml callback when setting up the views. <pre> Phery::instance()->views(array( 'section#container' => function($data, $params){ return PheryResponse::factory() ->render_view('html', array('extra data like titles, menus, etc')); } )); </pre> @return Phery
entailment
protected function before_user_func() { if ($this->config['error_reporting'] !== false) { set_error_handler(sprintf('%s::error_handler', __CLASS__), $this->config['error_reporting']); } if (empty($_POST['phery']['csrf'])) { $_POST['phery']['csrf'] = ''; } if ($this->csrf($_POST['phery']['csrf']) === false) { self::exception($this, 'Invalid CSRF token', self::ERROR_CSRF); } }
Initialize stuff before calling the AJAX function @return void
entailment
private function process_data($last_call) { $response = null; $error = null; $view = false; if (empty($_POST['phery'])) { return self::exception($this, 'Non-Phery AJAX request', self::ERROR_PROCESS); } if (!empty($_GET['_'])) { $this->data['requested'] = (int)$_GET['_']; unset($_GET['_']); } if (isset($_GET['_try_count'])) { $this->data['retries'] = (int)$_GET['_try_count']; unset($_GET['_try_count']); } $args = array(); $remote = false; if (!empty($_POST['phery']['remote'])) { $remote = $_POST['phery']['remote']; } if (!empty($_POST['phery']['submit_id'])) { $this->data['submit_id'] = "#{$_POST['phery']['submit_id']}"; } if ($remote !== false) { $this->data['remote'] = $remote; } if (!empty($_POST['args'])) { $args = get_magic_quotes_gpc() ? $this->stripslashes_recursive($_POST['args']) : $_POST['args']; if ($last_call === true) { unset($_POST['args']); } } foreach ($_POST['phery'] as $name => $post) { if (!isset($this->data[$name])) { $this->data[$name] = $post; } } if (count($this->callbacks['before'])) { foreach ($this->callbacks['before'] as $func) { if (($args = call_user_func($func, $args, $this->data, $this)) === false) { return false; } } } if (!empty($_POST['phery']['view'])) { $this->data['view'] = $_POST['phery']['view']; } if ($remote !== false) { if (isset($this->functions[$remote])) { if (isset($_POST['phery']['remote'])) { unset($_POST['phery']['remote']); } $this->before_user_func(); $response = call_user_func($this->functions[$remote], $args, $this->data, $this); foreach ($this->callbacks['after'] as $func) { if (call_user_func($func, $args, $this->data, $response, $this) === false) { return false; } } if (($response = self::respond($response, false)) === null) { $error = 'Response was void for function "' . htmlentities($remote, ENT_COMPAT, null, false) . '"'; } $_POST['phery']['remote'] = $remote; } else { if ($last_call) { self::exception($this, 'The function provided "' . htmlentities($remote, ENT_COMPAT, null, false) . '" isn\'t set', self::ERROR_PROCESS); } } } else { if (!empty($this->data['view']) && isset($this->views[$this->data['view']])) { $view = $this->data['view']; $this->before_user_func(); $response = call_user_func($this->views[$this->data['view']], $args, $this->data, $this); foreach ($this->callbacks['after'] as $func) { if (call_user_func($func, $args, $this->data, $response, $this) === false) { return false; } } if (($response = self::respond($response, false)) === null) { $error = 'Response was void for view "' . htmlentities($this->data['view'], ENT_COMPAT, null, false) . '"'; } } else { if ($last_call) { if (!empty($this->data['view'])) { self::exception($this, 'The provided view "' . htmlentities($this->data['view'], ENT_COMPAT, null, false) . '" isn\'t set', self::ERROR_PROCESS); } else { self::exception($this, 'Empty request', self::ERROR_PROCESS); } } } } if ($error !== null) { self::error_handler(E_NOTICE, $error, '', 0); } elseif ($response === null && $last_call & !$view) { $response = PheryResponse::factory(); } elseif ($response !== null) { ob_start(); if (!$this->config['return']) { echo $response; } } if (!$this->config['return'] && $this->config['exit_allowed'] === true) { if ($last_call || $response !== null) { exit; } } elseif ($this->config['return']) { self::flush(true); } if ($this->config['error_reporting'] !== false) { restore_error_handler(); } return $response; }
Process the requests if any @param boolean $last_call @return boolean
entailment
public function process($last_call = true) { if (self::is_ajax(true)) { // AJAX call return $this->process_data($last_call); } return true; }
Process the AJAX requests if any. @param bool $last_call Set this to false if any other further calls to process() will happen, otherwise it will exit @throws PheryException @return boolean Return false if any error happened
entailment
public function config($config = null) { $register_function = false; if (!empty($config)) { if (is_array($config)) { if (isset($config['exit_allowed'])) { $this->config['exit_allowed'] = (bool)$config['exit_allowed']; } if (isset($config['auto_session'])) { $this->config['auto_session'] = (bool)$config['auto_session']; } if (isset($config['return'])) { $this->config['return'] = (bool)$config['return']; } if (isset($config['set_always_available'])) { $this->config['set_always_available'] = (bool)$config['set_always_available']; } if (isset($config['exceptions'])) { $this->config['exceptions'] = (bool)$config['exceptions']; } if (isset($config['csrf'])) { $this->config['csrf'] = (bool)$config['csrf']; } if (isset($config['error_reporting'])) { if ($config['error_reporting'] !== false) { $this->config['error_reporting'] = (int)$config['error_reporting']; } else { $this->config['error_reporting'] = false; } $register_function = true; } if ($register_function || $this->init) { register_shutdown_function(sprintf('%s::shutdown_handler', __CLASS__), $this->config['error_reporting'] !== false); $this->init = false; } return $this; } elseif (!empty($config) && is_string($config) && isset($this->config[$config])) { return $this->config[$config]; } } return $this->config; }
Config the current instance of Phery <code> array( // Defaults to true, stop further script execution 'exit_allowed' => true|false, // Throw exceptions on errors 'exceptions' => true|false, // Return the responses in the process() call instead of echo'ing 'return' => true|false, // Error reporting temporarily using error_reporting(). 'false' disables // the error_reporting and wont try to catch any error. // Anything else than false will throw a PheryResponse->exception() with // the message 'error_reporting' => false|E_ALL|E_DEPRECATED|... // By default, the function Phery::instance()->set() will only // register functions when the current request is an AJAX call, // to save resources. In order to use Phery::instance()->get_function() // anytime, you need to set this config value to true 'set_always_available' => false|true ); </code> If you pass a string, it will return the current config for the key specified Anything else, will output the current config as associative array @param string|array $config Associative array containing the following options @return Phery|string|array
entailment
public static function instance(array $config = array()) { if (!(self::$instance instanceof Phery)) { self::$instance = new Phery($config); } else if ($config) { self::$instance->config($config); } return self::$instance; }
Generates just one instance. Useful to use in many included files. Chainable @param array $config Associative config array @see __construct() @see config() @static @return Phery
entailment
public function set(array $functions) { if ($this->config['set_always_available'] === false && !self::is_ajax(true)) { return $this; } if (isset($functions) && is_array($functions)) { foreach ($functions as $name => $func) { if (is_callable($func)) { $this->functions[$name] = $func; } else { self::exception($this, 'Provided function "' . $name . '" isnt a valid function or method', self::ERROR_SET); } } } else { self::exception($this, 'Call to "set" must be provided an array', self::ERROR_SET); } return $this; }
Sets the functions to respond to the ajax call. For security reasons, these functions should not be reacheable through POST/GET requests. These will be set only for AJAX requests as it will only be set in case of an ajax request, to save resources. You may set the config option "set_always_available" to true to always register the functions regardless of if it's an AJAX function or not going on. The answer/process function, should have the following structure: <code> function func($ajax_data, $callback_data, $phery){ $r = new PheryResponse; // or PheryResponse::factory(); // Sometimes the $callback_data will have an item called 'submit_id', // is the ID of the calling DOM element. // if (isset($callback_data['submit_id'])) { } // $phery will be the current phery instance that called this callback $r->jquery('#id')->animate(...); return $r; //Should always return the PheryResponse unless you are dealing with plain text } </code> @param array $functions An array of functions to register to the instance. <pre> array( 'function1' => 'function', 'function2' => array($this, 'method'), 'function3' => 'StaticClass::name', 'function4' => array(new ClassName, 'method'), 'function5' => function($data){} ); </pre> @return Phery
entailment
public function unset_function($name) { if (isset($this->functions[$name])) { unset($this->functions[$name]); } return $this; }
Unset a function previously set with set() @param string $name Name of the function @see set() @return Phery
entailment
public function get_function($function_name, array $args = array()) { if (isset($this->functions[$function_name])) { if (count($args)) { return call_user_func_array($this->functions[$function_name], $args); } return $this->functions[$function_name]; } return null; }
Get previously function set with set() method If you pass aditional arguments, the function will be executed and this function will return the PheryResponse associated with that function <pre> Phery::get_function('render', ['<html></html>'])->appendTo('body'); </pre> @param string $function_name The name of the function registed with set @param array $args Any arguments to pass to the function @see Phery::set() @return callable|array|string|PheryResponse|null
entailment
protected static function common_check(&$attributes, $include_method = true) { if (!empty($attributes['args'])) { $attributes['data-phery-args'] = json_encode($attributes['args']); unset($attributes['args']); } if (!empty($attributes['confirm'])) { $attributes['data-phery-confirm'] = $attributes['confirm']; unset($attributes['confirm']); } if (!empty($attributes['cache'])) { $attributes['data-phery-cache'] = "1"; unset($attributes['cache']); } if (!empty($attributes['target'])) { $attributes['data-phery-target'] = $attributes['target']; unset($attributes['target']); } if (!empty($attributes['related'])) { $attributes['data-phery-related'] = $attributes['related']; unset($attributes['related']); } if (!empty($attributes['phery-type'])) { $attributes['data-phery-type'] = $attributes['phery-type']; unset($attributes['phery-type']); } if (!empty($attributes['only'])) { $attributes['data-phery-only'] = $attributes['only']; unset($attributes['only']); } if (isset($attributes['clickable'])) { $attributes['data-phery-clickable'] = "1"; unset($attributes['clickable']); } if ($include_method) { if (isset($attributes['method'])) { $attributes['data-phery-method'] = $attributes['method']; unset($attributes['method']); } } $encoding = 'UTF-8'; if (isset($attributes['encoding'])) { $encoding = $attributes['encoding']; unset($attributes['encoding']); } return $encoding; }
Common check for all static factories @param array $attributes @param bool $include_method @return string
entailment
public static function link_to($content, $function, array $attributes = array(), Phery $phery = null, $no_close = false) { if ($phery && !isset($phery->functions[$function])) { self::exception($phery, 'The function "' . $function . '" provided in "link_to" hasnt been set', self::ERROR_TO); } $tag = 'a'; if (isset($attributes['tag'])) { $tag = $attributes['tag']; unset($attributes['tag']); } $encoding = self::common_check($attributes); if ($function) { $attributes['data-phery-remote'] = $function; } $ret = array(); $ret[] = "<{$tag}"; foreach ($attributes as $attribute => $value) { $ret[] = "{$attribute}=\"" . htmlentities($value, ENT_COMPAT, $encoding, false) . "\""; } if (!in_array(strtolower($tag), array('img', 'input', 'iframe', 'hr', 'area', 'embed', 'keygen'))) { $ret[] = ">{$content}"; if (!$no_close) { $ret[] = "</{$tag}>"; } } else { $ret[] = "/>"; } return join(' ', $ret); }
Helper function that generates an ajax link, defaults to "A" tag @param string $content The content of the link. This is ignored for self closing tags, img, input, iframe @param string $function The PHP function assigned name on Phery::set() @param array $attributes Extra attributes that can be passed to the link, like class, style, etc <pre> array( // Display confirmation on click 'confirm' => 'Are you sure?', // The tag for the item, defaults to a. If the tag is set to img, the // 'src' must be set in attributes parameter 'tag' => 'a', // Define another URI for the AJAX call, this defines the HREF of A 'href' => '/path/to/url', // Extra arguments to pass to the AJAX function, will be stored // in the data-phery-args attribute as a JSON notation 'args' => array(1, "a"), // Set the "href" attribute for non-anchor (a) AJAX tags (like buttons or spans). // Works for A links too, but it won't function without javascript, through data-phery-target 'target' => '/default/ajax/controller', // Define the data-phery-type for the expected response, json, xml, text, etc 'phery-type' => 'json', // Enable clicking on structural HTML, like DIV, HEADER, HGROUP, etc 'clickable' => true, // Force cache of the response 'cache' => true, // Aggregate data from other DOM elements, can be forms, inputs (textarea, selects), // pass multiple selectors, like "#input1,#form1,~ input:hidden,select.job" // that are searched in this order: // - $(this).find(related) // - $(related) // So you can use sibling, children selectors, like ~, +, >, :parent // You can also, through Javascript, append a jQuery object to the related, using // $('#element').phery('data', 'related', $('#other_element')); 'related' => true, // Disables the AJAX on element while the last action is not completed 'only' => true, // Set the encoding of the data, defaults to UTF-8 'encoding' => 'UTF-8', // Set the method (for restful responses) 'method' => 'PUT' ); </pre> @param Phery $phery Pass the current instance of phery, so it can check if the functions are defined, and throw exceptions @param boolean $no_close Don't close the tag, useful if you want to create an AJAX DIV with a lot of content inside, but the DIV itself isn't clikable <pre> <?php echo Phery::link_to('', 'remote', array('target' => '/another-url', 'args' => array('id' => 1), 'class' => 'ajaxified'), null, true); ?> <p>This new content</p> <div class="result></div> </div> <?php echo Phery::link_to('', 'remote', array('target' => '/another-url', 'args' => array('id' => 2), 'class' => 'ajaxified'), null, true); ?> <p>Another content will have div result filled</p> <div class="result></div> </div> <script> $('.ajaxified').phery('remote'); </script> </pre> @static @return string The mounted HTML tag
entailment
public static function form_for($action, $function, array $attributes = array(), Phery $phery = null) { if (!$function) { self::exception($phery, 'The "function" argument must be provided to "form_for"', self::ERROR_TO); return ''; } if ($phery && !isset($phery->functions[$function])) { self::exception($phery, 'The function "' . $function . '" provided in "form_for" hasnt been set', self::ERROR_TO); } $encoding = self::common_check($attributes, false); if (isset($attributes['submit'])) { $attributes['data-phery-submit'] = json_encode($attributes['submit']); unset($attributes['submit']); } $ret = array(); $ret[] = '<form method="POST" action="' . $action . '" data-phery-remote="' . $function . '"'; foreach ($attributes as $attribute => $value) { $ret[] = "{$attribute}=\"" . htmlentities($value, ENT_COMPAT, $encoding, false) . "\""; } $ret[] = '>'; return join(' ', $ret); }
Create a <form> tag with ajax enabled. Must be closed manually with </form> @param string $action where to go, can be empty @param string $function Registered function name @param array $attributes Configuration of the element plus any HTML attributes <pre> array( //Confirmation dialog 'confirm' => 'Are you sure?', // Type of call, defaults to JSON (to use PheryResponse) 'phery-type' => 'json', // 'all' submits all elements on the form, even empty ones // 'disabled' enables submitting disabled elements 'submit' => array('all' => true, 'disabled' => true), // Disables the AJAX on element while the last action is not completed 'only' => true, // Set the encoding of the data, defaults to UTF-8 'encoding' => 'UTF-8', ); </pre> @param Phery $phery Pass the current instance of phery, so it can check if the functions are defined, and throw exceptions @static @return string The mounted &lt;form&gt; HTML tag
entailment
public static function select_for($function, array $items, array $attributes = array(), Phery $phery = null) { if ($phery && !isset($phery->functions[$function])) { self::exception($phery, 'The function "' . $function . '" provided in "select_for" hasnt been set', self::ERROR_TO); } $encoding = self::common_check($attributes); $selected = array(); if (isset($attributes['selected'])) { if (is_array($attributes['selected'])) { // multiple select $selected = $attributes['selected']; } else { // single select $selected = array($attributes['selected']); } unset($attributes['selected']); } if (isset($attributes['multiple'])) { $attributes['multiple'] = 'multiple'; } $ret = array(); $ret[] = '<select ' . ($function ? 'data-phery-remote="' . $function . '"' : ''); foreach ($attributes as $attribute => $value) { $ret[] = "{$attribute}=\"" . htmlentities($value, ENT_COMPAT, $encoding, false) . "\""; } $ret[] = '>'; foreach ($items as $value => $text) { $_value = 'value="' . htmlentities($value, ENT_COMPAT, $encoding, false) . '"'; if (in_array($value, $selected)) { $_value .= ' selected="selected"'; } $ret[] = "<option " . ($_value) . ">{$text}</option>\n"; } $ret[] = '</select>'; return join(' ', $ret); }
Create a <select> element with ajax enabled "onchange" event. @param string $function Registered function name @param array $items Options for the select, 'value' => 'text' representation @param array $attributes Configuration of the element plus any HTML attributes <pre> array( // Confirmation dialog 'confirm' => 'Are you sure?', // Type of call, defaults to JSON (to use PheryResponse) 'phery-type' => 'json', // The URL where it should call, translates to data-phery-target 'target' => '/path/to/php', // Extra arguments to pass to the AJAX function, will be stored // in the args attribute as a JSON notation, translates to data-phery-args 'args' => array(1, "a"), // Set the encoding of the data, defaults to UTF-8 'encoding' => 'UTF-8', // Disables the AJAX on element while the last action is not completed 'only' => true, // The current selected value, or array(1,2) for multiple 'selected' => 1 // Set the method (for restful responses) 'method' => 'PUT' ); </pre> @param Phery $phery Pass the current instance of phery, so it can check if the functions are defined, and throw exceptions @static @return string The mounted &lt;select&gt; with &lt;option&gt;s inside
entailment
public static function coalesce($args) { $args = func_get_args(); foreach ($args as &$arg) { if (isset($arg) && !empty($arg)) { return $arg; } } return null; }
Utility function taken from MYSQL. To not raise any E_NOTICES (if enabled in your error reporting), call it with @ before the variables. Eg.: Phery::coalesce(@$var1, @$var['asdf']); @param mixed $args,... Any number of arguments @return mixed
entailment
public function compile() { $value = $this->value(); if ( ! empty($this->parameters)) { $params = $this->parameters; $value = strtr($value, $params); } return $value; }
Compile function and return it. Replaces any parameters with their given values. @return string
entailment
public function stem($word) { // we do ALL in UTF-8 if (! Utf8::check($word)) { throw new \Exception('Word must be in UTF-8'); } if (Utf8::strlen($word) < 3) { return $word; } $this->word = Utf8::strtolower($word); // exceptions if (null !== ($word = $this->exception1())) { return $word; } $this->plainVowels = implode('', self::$vowels); // Remove initial ', if present. $first = Utf8::substr($this->word, 0, 1); if ($first == "'") { $this->word = Utf8::substr($this->word, 1); } // Set initial y, or y after a vowel, to Y if ($first == 'y') { $this->word = preg_replace('#^y#u', 'Y', $this->word); } $this->word = preg_replace('#(['.$this->plainVowels.'])y#u', '$1Y', $this->word); $this->r1(); $this->exceptionR1(); $this->r2(); $this->step0(); $this->step1a(); // exceptions 2 if (null !== ($word = $this->exception2())) { return $word; } $this->step1b(); $this->step1c(); $this->step2(); $this->step3(); $this->step4(); $this->step5(); $this->finish(); return $this->word; }
{@inheritdoc}
entailment
private function step0() { if ( ($position = $this->search(array("'s'", "'s", "'"))) !== false) { $this->word = Utf8::substr($this->word, 0, $position); } }
Step 0 Remove ', 's, 's'
entailment
private function step1b() { // eed eedly+ // replace by ee if in R1 if ( ($position = $this->search(array('eedly', 'eed'))) !== false) { if ($this->inR1($position)) { $this->word = preg_replace('#(eedly|eed)$#u', 'ee', $this->word); } return true; } // ed edly+ ing ingly+ // delete if the preceding word part contains a vowel, and after the deletion: // if the word ends at, bl or iz add e (so luxuriat -> luxuriate), or // if the word ends with a double remove the last letter (so hopp -> hop), or // if the word is short, add e (so hop -> hope) if ( ($position = $this->search(array('edly', 'ingly', 'ed', 'ing'))) !== false) { for ($i=0; $i<$position; $i++) { $letter = Utf8::substr($this->word, $i, 1); if (in_array($letter, self::$vowels)) { $this->word = Utf8::substr($this->word, 0, $position); if ($this->search(array('at', 'bl', 'iz')) !== false) { $this->word .= 'e'; } elseif ( ($position2 = $this->search(self::$doubles)) !== false) { $this->word = Utf8::substr($this->word, 0, ($position2+1)); } elseif ($this->isShort()) { $this->word .= 'e'; } return true; } } return true; } return false; }
Step 1b
entailment
private function step1c() { // replace suffix y or Y by i if preceded by a non-vowel // which is not the first letter of the word (so cry -> cri, by -> by, say -> say) $length = Utf8::strlen($this->word); if ($length < 3) { return true; } if ( ($position = $this->search(array('y', 'Y'))) !== false) { $before = $position - 1; $letter = Utf8::substr($this->word, $before, 1); if (! in_array($letter, self::$vowels)) { $this->word = preg_replace('#(y|Y)$#u', 'i', $this->word); } return true; } return false; }
Step 1c: *
entailment
private function step2() { // iveness iviti: replace by ive if ( ($position = $this->search(array('iveness', 'iviti'))) !== false) { if ($this->inR1($position)) { $this->word = preg_replace('#(iveness|iviti)$#u', 'ive', $this->word); } return true; } // ousli ousness: replace by ous if ( ($position = $this->search(array('ousli', 'ousness'))) !== false) { if ($this->inR1($position)) { $this->word = preg_replace('#(ousli|ousness)$#u', 'ous', $this->word); } return true; } // izer ization: replace by ize if ( ($position = $this->search(array('izer', 'ization'))) !== false) { if ($this->inR1($position)) { $this->word = preg_replace('#(izer|ization)$#u', 'ize', $this->word); } return true; } // ational ation ator: replace by ate if ( ($position = $this->search(array('ational', 'ation', 'ator'))) !== false) { if ($this->inR1($position)) { $this->word = preg_replace('#(ational|ation|ator)$#u', 'ate', $this->word); } return true; } // biliti bli+: replace by ble if ( ($position = $this->search(array('biliti', 'bli'))) !== false) { if ($this->inR1($position)) { $this->word = preg_replace('#(biliti|bli)$#u', 'ble', $this->word); } return true; } // lessli+: replace by less if ( ($position = $this->search(array('lessli'))) !== false) { if ($this->inR1($position)) { $this->word = preg_replace('#(lessli)$#u', 'less', $this->word); } return true; } // fulness: replace by ful if ( ($position = $this->search(array('fulness', 'fulli'))) !== false) { if ($this->inR1($position)) { $this->word = preg_replace('#(fulness|fulli)$#u', 'ful', $this->word); } return true; } // tional: replace by tion if ( ($position = $this->search(array('tional'))) !== false) { if ($this->inR1($position)) { $this->word = preg_replace('#(tional)$#u', 'tion', $this->word); } return true; } // alism aliti alli: replace by al if ( ($position = $this->search(array('alism', 'aliti', 'alli'))) !== false) { if ($this->inR1($position)) { $this->word = preg_replace('#(alism|aliti|alli)$#u', 'al', $this->word); } return true; } // enci: replace by ence if ( ($position = $this->search(array('enci'))) !== false) { if ($this->inR1($position)) { $this->word = preg_replace('#(enci)$#u', 'ence', $this->word); } return true; } // anci: replace by ance if ( ($position = $this->search(array('anci'))) !== false) { if ($this->inR1($position)) { $this->word = preg_replace('#(anci)$#u', 'ance', $this->word); } return true; } // abli: replace by able if ( ($position = $this->search(array('abli'))) !== false) { if ($this->inR1($position)) { $this->word = preg_replace('#(abli)$#u', 'able', $this->word); } return true; } // entli: replace by ent if ( ($position = $this->search(array('entli'))) !== false) { if ($this->inR1($position)) { $this->word = preg_replace('#(entli)$#u', 'ent', $this->word); } return true; } // ogi+: replace by og if preceded by l if ( ($position = $this->search(array('ogi'))) !== false) { if ($this->inR1($position)) { $before = $position - 1; $letter = Utf8::substr($this->word, $before, 1); if ($letter == 'l') { $this->word = preg_replace('#(ogi)$#u', 'og', $this->word); } } return true; } // li+: delete if preceded by a valid li-ending if ( ($position = $this->search(array('li'))) !== false) { if ($this->inR1($position)) { // a letter for you $letter = Utf8::substr($this->word, ($position-1), 1); if (in_array($letter, self::$liEnding)) { $this->word = Utf8::substr($this->word, 0, $position); } } return true; } return false; }
Step 2 Search for the longest among the following suffixes, and, if found and in R1, perform the action indicated.
entailment
public function step3() { // ational+: replace by ate if ($this->searchIfInR1(array('ational')) !== false) { $this->word = preg_replace('#(ational)$#u', 'ate', $this->word); return true; } // tional+: replace by tion if ($this->searchIfInR1(array('tional')) !== false) { $this->word = preg_replace('#(tional)$#u', 'tion', $this->word); return true; } // alize: replace by al if ($this->searchIfInR1(array('alize')) !== false) { $this->word = preg_replace('#(alize)$#u', 'al', $this->word); return true; } // icate iciti ical: replace by ic if ($this->searchIfInR1(array('icate', 'iciti', 'ical')) !== false) { $this->word = preg_replace('#(icate|iciti|ical)$#u', 'ic', $this->word); return true; } // ful ness: delete if ( ($position = $this->searchIfInR1(array('ful', 'ness'))) !== false) { $this->word = Utf8::substr($this->word, 0, $position); return true; } // ative*: delete if in R2 if ( (($position = $this->searchIfInR1(array('ative'))) !== false) && ($this->inR2($position)) ) { $this->word = Utf8::substr($this->word, 0, $position); return true; } return false; }
Step 3: Search for the longest among the following suffixes, and, if found and in R1, perform the action indicated.
entailment
public function step4() { // ement ance ence able ible ant ment ent ism ate iti ous ive ize al er ic // delete if ( ($position = $this->search(array( 'ance', 'ence', 'ement', 'able', 'ible', 'ant', 'ment', 'ent', 'ism', 'ate', 'iti', 'ous', 'ive', 'ize', 'al', 'er', 'ic'))) !== false) { if ($this->inR2($position)) { $this->word = Utf8::substr($this->word, 0, $position); } return true; } // ion // delete if preceded by s or t if ( ($position = $this->searchIfInR2(array('ion'))) !== false) { $before = $position - 1; $letter = Utf8::substr($this->word, $before, 1); if ($letter == 's' || $letter == 't') { $this->word = Utf8::substr($this->word, 0, $position); } return true; } return false; }
Step 4 Search for the longest among the following suffixes, and, if found and in R2, perform the action indicated.
entailment
public function step5() { // e // delete if in R2, or in R1 and not preceded by a short syllable if ( ($position = $this->search(array('e'))) !== false) { if ($this->inR2($position)) { $this->word = Utf8::substr($this->word, 0, $position); } elseif ($this->inR1($position)) { if ( (! $this->searchShortSyllabe(-4, 3)) && (! $this->searchShortSyllabe(-3, 2)) ) { $this->word = Utf8::substr($this->word, 0, $position); } } return true; } // l // delete if in R2 and preceded by l if ( ($position = $this->searchIfInR2(array('l'))) !== false) { $before = $position - 1; $letter = Utf8::substr($this->word, $before, 1); if ($letter == 'l') { $this->word = Utf8::substr($this->word, 0, $position); } return true; } return false; }
Step 5: * Search for the the following suffixes, and, if found, perform the action indicated.
entailment
private function exception1() { $exceptions = array( 'skis' => 'ski', 'skies' => 'sky', 'dying' => 'die', 'lying' => 'lie', 'tying' => 'tie', 'idly' => 'idl', 'gently' => 'gentl', 'ugly' => 'ugli', 'early' => 'earli', 'only' => 'onli', 'singly' => 'singl', // invariants 'sky' => 'sky', 'news' => 'news', 'howe' => 'howe', 'atlas' => 'atlas', 'cosmos' => 'cosmos', 'bias' => 'bias', 'andes' => 'andes' ); if (isset($exceptions[$this->word])) { return $exceptions[$this->word]; } return null; }
1/ Stem certain special words as follows, 2/ If one of the following is found, leave it invariant,
entailment
private function exception2() { $exceptions = array( 'inning' => 'inning', 'outing' => 'outing', 'canning' => 'canning', 'herring' => 'herring', 'earring' => 'earring', 'proceed' => 'proceed', 'exceed' => 'exceed', 'succeed' => 'succeed' ); if (isset($exceptions[$this->word])) { return $exceptions[$this->word]; } return null; }
Following step 1a, leave the following invariant,
entailment
private function isShort() { $length = Utf8::strlen($this->word); return ( ($this->searchShortSyllabe(-3, 3) || $this->searchShortSyllabe(-2, 2)) && ($length == $this->r1Index) ); }
A word is called short if it ends in a short syllable, and if R1 is null. Note : R1 not really null, but the word at this state must be smaller than r1 index @return boolean
entailment
private function searchShortSyllabe($from, $nbLetters) { $length = Utf8::strlen($this->word); if ($from < 0) { $from = $length + $from; } if ($from < 0) { $from = 0; } // (a) is just for beginning of the word if ( ($nbLetters == 2) && ($from != 0) ) { return false; } $first = Utf8::substr($this->word, $from, 1); $second = Utf8::substr($this->word, ($from+1), 1); if ($nbLetters == 2) { if ( (in_array($first, self::$vowels)) && (!in_array($second, self::$vowels)) ) { return true; } } $third = Utf8::substr($this->word, ($from+2), 1); if ( (!in_array($first, self::$vowels)) && (in_array($second, self::$vowels)) && (!in_array($third, array_merge(self::$vowels, array('x', 'Y', 'w'))))) { return true; } return false; }
Define a short syllable in a word as either (a) a vowel followed by a non-vowel other than w, x or Y and preceded by a non-vowel, or * (b) a vowel at the beginning of the word followed by a non-vowel. So rap, trap, entrap end with a short syllable, and ow, on, at are classed as short syllables. But uproot, bestow, disturb do not end with a short syllable.
entailment
public function set_config(array $config) { if (isset($config['convert_integers'])) { $this->config['convert_integers'] = (bool)$config['convert_integers']; } if (isset($config['typecast_objects'])) { $this->config['typecast_objects'] = (bool)$config['typecast_objects']; } return $this; }
Change the config for this response You may pass in an associative array of your config @param array $config <pre> array( 'convert_integers' => true/false 'typecast_objects' => true/false </pre> @return PheryResponse
entailment
protected function set_internal_counter($type, $force = false) { $last = $this->last_selector; if ($force && $last !== null && !isset($this->data[$last])) { $this->data[$last] = array(); } $this->last_selector = '{' . $type . (self::$internal_count++) . '}'; return $last; }
Increment the internal counter, so there are no conflicting stacked commands @param string $type Selector @param boolean $force Force unajusted selector into place @return string The previous overwritten selector
entailment
public function renew_csrf(Phery $instance) { if ($instance->config('csrf') === true) { $this->cmd(13, array($instance->csrf())); } return $this; }
Renew the CSRF token on a given Phery instance Resets any selectors that were being chained before @param Phery $instance Instance of Phery @return PheryResponse
entailment
public function set_response_name($name) { if (!empty($this->name)) { unset(self::$responses[$this->name]); } $this->name = $name; self::$responses[$this->name] = $this; return $this; }
Set the name of this response @param string $name Name of current response @return PheryResponse
entailment
public function phery_broadcast($name, array $params = array()) { $this->last_selector = null; return $this->cmd(12, array($name, array($this->typecast($params, true, true)), true)); }
Broadcast a remote message to the client to all elements that are subscribed to them. This removes the current selector if any @param string $name Name of the browser subscribed topic on the element @param array [$params] Any params to pass to the subscribed topic @return PheryResponse
entailment
public function unless($condition, $remote = false) { if (!$remote && !($condition instanceof PheryFunction) && !($condition instanceof PheryResponse)) { $this->matched = !$condition; } else { $this->set_internal_counter('!', true); $this->cmd(0xff, array($this->typecast($condition, true, true))); } return $this; }
Borrowed from Ruby, the next imediate instruction will be executed unless it matches this criteria. <code> $count = 3; PheryResponse::factory() // if not $count equals 2 then ->unless($count === 2) ->call('func'); // This won't trigger, $count is 2 </code> <code> PheryResponse::factory('.widget') ->unless(PheryFunction::factory('return !this.hasClass("active");'), true) ->remove(); // This won't remove if the element have the active class </code> @param boolean|PheryFunction $condition When not remote, can be any criteria that evaluates to FALSE. When it's remote, if passed a PheryFunction, it will skip the next iteration unless the return value of the PheryFunction is false. Passing a PheryFunction automatically sets $remote param to true @param bool $remote Instead of doing it in the server side, do it client side, for example, append something ONLY if an element exists. The context (this) of the function will be the last selected element or the calling element. @return PheryResponse
entailment
public static function files($group = false) { $result = array(); foreach ($_FILES as $name => $keys) { if (is_array($keys)) { if (is_array($keys['name'])) { $len = count($keys['name']); for ($i = 0; $i < $len; $i++) { $result[$name][$i] = array( 'name' => $keys['name'][$i], 'tmp_name' => $keys['tmp_name'][$i], 'type' => $keys['type'][$i], 'error' => $keys['error'][$i], 'size' => $keys['size'][$i], ); } } else { $result[$name] = array( $keys ); } } } return $group !== false && isset($result[$group]) ? $result[$group] : $result; }
This helper function is intended to normalize the $_FILES array, because when uploading multiple files, the order gets messed up. The result will always be in the format: <code> array( 'name of the file input' => array( array( 'name' => ..., 'tmp_name' => ..., 'type' => ..., 'error' => ..., 'size' => ..., ), array( 'name' => ..., 'tmp_name' => ..., 'type' => ..., 'error' => ..., 'size' => ..., ), ) ); </code> So you can always do like (regardless of one or multiple files uploads) <code> <input name="avatar" type="file" multiple> <input name="pic" type="file"> <?php foreach(PheryResponse::files('avatar') as $index => $file){ if (is_uploaded_file($file['tmp_name'])){ //... } } foreach(PheryResponse::files() as $field => $group){ foreach ($group as $file){ if (is_uploaded_file($file['tmp_name'])){ if ($field === 'avatar') { //... } else if ($field === 'pic') { //... } } } } ?> </code> If no files were uploaded, returns an empty array. @param string|bool $group Pluck out the file group directly @return array
entailment
public static function set_global($name, $value = null) { if (isset($name) && is_array($name)) { foreach ($name as $n => $v) { self::$global[$n] = $v; } } else { self::$global[$name] = $value; } }
Set a global value that can be accessed through $pheryresponse['value'] It's available in all responses, and can also be acessed using self['value'] @param array|string Key => value combination or the name of the global @param mixed $value [Optional]
entailment
public function offsetSet($index, $newval) { if ($index === null) { $this[] = $newval; } else { parent::offsetSet($index, $newval); } }
Set local variables, will be available only in this instance @param string|int|null $index @param mixed $newval @return void
entailment
public function offsetGet($index) { if (parent::offsetExists($index)) { return parent::offsetGet($index); } if (isset(self::$global[$index])) { return self::$global[$index]; } return null; }
Return null if no value @param mixed $index @return mixed|null
entailment
public static function get_response($name) { if (isset(self::$responses[$name]) && self::$responses[$name] instanceof PheryResponse) { return self::$responses[$name]; } return null; }
Get a response by name @param string $name @return PheryResponse|null
entailment
public function get_merged($name) { if (isset($this->merged[$name])) { if (isset(self::$responses[$name])) { return self::$responses[$name]; } $response = new PheryResponse; $response->data = $this->merged[$name]; return $response; } return null; }
Get merged response data as a new PheryResponse. This method works like a constructor if the previous response was destroyed @param string $name Name of the merged response @return PheryResponse|null
entailment
public function phery_remote($remote, $args = array(), $attr = array(), $directCall = true) { $this->set_internal_counter('-'); return $this->cmd(0xff, array( $remote, $args, $attr, $directCall )); }
Same as phery.remote() @param string $remote Function @param array $args Arguments to pass to the @param array $attr Here you may set like method, target, type, cache, proxy @param boolean $directCall Setting to false returns the jQuery object, that can bind events, append to DOM, etc @return PheryResponse
entailment
public function set_var($variable, $data) { $this->last_selector = null; if (!empty($data) && is_array($data)) { foreach ($data as $name => $d) { $data[$name] = $this->typecast($d, true, true); } } else { $data = $this->typecast($data, true, true); } return $this->cmd(9, array( !is_array($variable) ? array($variable) : $variable, array($data) )); }
Set a global variable, that can be accessed directly through window object, can set properties inside objects if you pass an array as the variable. If it doesn't exist it will be created <code> // window.customer_info = {'name': 'John','surname': 'Doe', 'age': 39} PheryResponse::factory()->set_var('customer_info', array('name' => 'John', 'surname' => 'Doe', 'age' => 39)); </code> <code> // window.customer_info.name = 'John' PheryResponse::factory()->set_var(array('customer_info','name'), 'John'); </code> @param string|array $variable Global variable name @param mixed $data Any data @return PheryResponse
entailment
public function unset_var($variable) { $this->last_selector = null; return $this->cmd(9, array( !is_array($variable) ? array($variable) : $variable, )); }
Delete a global variable, that can be accessed directly through window, can unset object properties, if you pass an array <code> PheryResponse::factory()->unset('customer_info'); </code> <code> PheryResponse::factory()->unset(array('customer_info','name')); // translates to delete customer_info['name'] </code> @param string|array $variable Global variable name @return PheryResponse
entailment
public function remove_selector($selector) { if ((is_string($selector) || is_int($selector)) && isset($this->data[$selector])) { unset($this->data[$selector]); } return $this; }
Remove a batch of calls for a selector. Won't remove for merged responses. Passing an integer, will remove commands, like dump_vars, call, etc, in the order they were called @param string|int $selector @return PheryResponse
entailment
public function merge($phery_response) { if (is_string($phery_response)) { if (isset(self::$responses[$phery_response])) { $this->merged[self::$responses[$phery_response]->name] = self::$responses[$phery_response]->data; } } elseif ($phery_response instanceof PheryResponse) { $this->merged[$phery_response->name] = $phery_response->data; } return $this; }
Merge another response to this one. Selectors with the same name will be added in order, for example: <code> function process() { $response = PheryResponse::factory('a.links')->remove(); // $response will execute before // there will be no more "a.links" in the DOM, so the addClass() will fail silently // to invert the order, merge $response to $response2 $response2 = PheryResponse::factory('a.links')->addClass('red'); return $response->merge($response2); } </code> @param PheryResponse|string $phery_response Another PheryResponse object or a name of response @return PheryResponse
entailment
public function unmerge($phery_response) { if (is_string($phery_response)) { if (isset(self::$responses[$phery_response])) { unset($this->merged[self::$responses[$phery_response]->name]); } } elseif ($phery_response instanceof PheryResponse) { unset($this->merged[$phery_response->name]); } elseif ($phery_response === true) { $this->merged = array(); } return $this; }
Remove a previously merged response, if you pass TRUE will removed all merged responses @param PheryResponse|string|boolean $phery_response @return PheryResponse
entailment
public function print_vars($vars) { $this->last_selector = null; $args = array(); foreach (func_get_args() as $name => $arg) { if (is_object($arg)) { $arg = get_object_vars($arg); } $args[$name] = array(var_export($arg, true)); } return $this->cmd(6, $args); }
Pretty print to console.log @param mixed $vars,... Any var @return PheryResponse
entailment
public function dump_vars($vars) { $this->last_selector = null; $args = array(); foreach (func_get_args() as $index => $func) { if ($func instanceof PheryResponse || $func instanceof PheryFunction) { $args[$index] = array($this->typecast($func, true, true)); } elseif (is_object($func)) { $args[$index] = array(get_object_vars($func)); } else { $args[$index] = array($func); } } return $this->cmd(6, $args); }
Dump var to console.log @param mixed $vars,... Any var @return PheryResponse
entailment
public function jquery($selector, array $constructor = array()) { if ($selector) { $this->last_selector = $selector; } if (isset($selector) && is_string($selector) && count($constructor) && substr($selector, 0, 1) === '<') { foreach ($constructor as $name => $value) { $this->$name($value); } } return $this; }
Sets the jQuery selector, so you can chain many calls to it. <code> PheryResponse::factory() ->jquery('.slides') ->fadeTo(0,0) ->css(array('top' => '10px', 'left' => '90px')); </code> For creating an element <code> PheryResponse::factory() ->jquery('.slides', array( 'css' => array( 'left': '50%', 'textDecoration': 'underline' ) )) ->appendTo('body'); </code> @param string $selector Sets the current selector for subsequent chaining, like you would using $() @param array $constructor Only available if you are creating a new element, like $('&lt;p/&gt;', {'class': 'classname'}) @return PheryResponse
entailment
public function alert($msg) { if (is_array($msg)) { $msg = join("\n", $msg); } $this->last_selector = null; return $this->cmd(1, array($this->typecast($msg, true))); }
Show an alert box @param string $msg Message to be displayed @return PheryResponse
entailment
public function cmd($cmd, array $args = array(), $selector = null) { if (!$this->matched) { $this->matched = true; return $this; } $selector = Phery::coalesce($selector, $this->last_selector); if ($selector === null) { $this->data['0' . ($this->internal_cmd_count++)] = array( 'c' => $cmd, 'a' => $args ); } else { if (!isset($this->data[$selector])) { $this->data[$selector] = array(); } $this->data[$selector][] = array( 'c' => $cmd, 'a' => $args ); } if ($this->restore !== null) { $this->last_selector = $this->restore; $this->restore = null; } return $this; }
Add a command to the response @param int|string|array $cmd Integer for command, see Phery.js for more info @param array $args Array to pass to the response @param string $selector Insert the jquery selector @return PheryResponse
entailment
public function attr($attr, $data, $selector = null) { return $this->cmd('attr', array( $attr, $data ), $selector); }
Set the attribute of a jQuery selector Example: <code> PheryResponse::factory() ->attr('href', 'http://url.com', 'a#link-' . $args['id']); </code> @param string $attr HTML attribute of the item @param string $data Value @param string $selector [optional] Provide the jQuery selector directly @return PheryResponse
entailment
public function exception($msg, $data = null) { $this->last_selector = null; return $this->cmd(7, array( $msg, $data )); }
Trigger the phery:exception event on the calling element with additional data @param string $msg Message to pass to the exception @param mixed $data Any data to pass, can be anything @return PheryResponse
entailment
public function call($func_name, $args = null) { $args = func_get_args(); array_shift($args); $this->last_selector = null; return $this->cmd(2, array( !is_array($func_name) ? array($func_name) : $func_name, $args )); }
Call a javascript function. Warning: calling this function will reset the selector jQuery selector previously stated The context of `this` call is the object in the $func_name path or window, if not provided @param string|array $func_name Function name. If you pass a string, it will be accessed on window.func. If you pass an array, it will access a member of an object, like array('object', 'property', 'function') @param mixed $args,... Any additional arguments to pass to the function @return PheryResponse
entailment
public function apply($func_name, array $args = array()) { $this->last_selector = null; return $this->cmd(2, array( !is_array($func_name) ? array($func_name) : $func_name, $args )); }
Call 'apply' on a javascript function. Warning: calling this function will reset the selector jQuery selector previously stated The context of `this` call is the object in the $func_name path or window, if not provided @param string|array $func_name Function name @param array $args Any additional arguments to pass to the function @return PheryResponse
entailment
public function script($script) { $this->last_selector = null; if (is_array($script)) { $script = join("\n", $script); } return $this->cmd(3, array( $script )); }
Compile a script and call it on-the-fly. There is a closure on the executed function, so to reach out global variables, you need to use window.variable Warning: calling this function will reset the selector jQuery selector previously set @param string|array $script Script content. If provided an array, it will be joined with \n <pre> PheryResponse::factory() ->script(array("if (confirm('Are you really sure?')) $('*').remove()")); </pre> @return PheryResponse
entailment
public function render_view($html, $data = array()) { $this->last_selector = null; if (is_array($html)) { $html = join("\n", $html); } return $this->cmd(5, array( $this->typecast($html, true, true), $data )); }
Render a view to the container previously specified @param string $html HTML to be replaced in the container @param array $data Array of data to pass to the before/after functions set on Phery.view @see Phery.view() on JS @return PheryResponse
entailment