public function testSetId() { $this->ormMock->expects($this->once())->method('setValue')->with('id', 2); $this->ormMock->expects($this->any())->method('getValue')->with('id')->will($this->returnValue(2)); $this->model->id = 2; $this->assertEquals(2, $this->model->getId()); }
/** * Find if two objects represent the same model * * @param Model $model The model to compare * @return bool */ public function isSameAs(Model $model) { if (!$this->isValid() || !$model->isValid()) { return false; } $sameType = $this instanceof $model || $model instanceof $this; return $sameType && $this->getId() === $model->getId(); }
/** * Test * * @return void */ public function testDocumentCommentWithPostData() { $this->dispatch('/admin/module/blog/document-comment/' . $this->document->getId(), 'POST', array('comment' => array('1' => array('delete' => true), '2' => array('message' => true, 'wrong-name' => false)))); $this->assertResponseStatusCode(302); $this->assertModuleName('Blog'); $this->assertControllerName('BlogController'); $this->assertControllerClass('IndexController'); $this->assertMatchedRouteName('module/blog/document-comment'); }
/** * Get the name of any model * * @param \Model $model * @return string The name of the model */ private function getModelName($model) { if ($model instanceof \NamedModel) { return $model->getName(); } if ($model instanceof \AliasModel) { return $model->getAlias(); } return $model->getId(); }
/** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { if (isset($options['include'])) { $this->include = $options['include']; } if (isset($options['multiple'])) { $this->multiple = $options['multiple']; } if ($this->include && !$this->multiple) { throw new \LogicException("You can't include an object in a single selection!"); } $builderName = ucfirst($builder->getName()); // TODO: Use a more accurate placeholder $placeholder = $this->multiple ? 'brad, kierra, ...' : null; if ($this->include) { $exclude = $this->include->getType() . ':' . $this->include->getId(); } else { $exclude = null; } // Model IDs that will be manipulated by javascript $builder->add('ids', 'hidden', array('attr' => array('class' => 'select2-compatible', 'data-exclude' => $exclude, 'data-label' => $builderName, 'data-multiple' => $this->multiple, 'data-required' => $options['required']))); // Model name inputs that will be edited by users if javascript is // disabled foreach ($this->types as $type) { $pluralType = $this->multiple ? Inflector::pluralize($type) : $type; $label = count($this->types) > 1 ? "{$builderName} {$pluralType}" : $builderName; $builder->add($builder->create($type, 'text', array('attr' => array('class' => 'model-select', 'data-type' => $type, 'placeholder' => $placeholder), 'label' => $label, 'required' => false))); } if ($this->multiple) { $transformer = new MultipleAdvancedModelTransformer($this->types); if ($this->include) { $transformer->addInclude($this->include); } } else { $transformer = new SingleAdvancedModelTransformer($this->types); } $builder->addViewTransformer($transformer); // Make sure we can change the values provided by the user $builder->setDataLocked(false); }
/** * This returns all models sorted by Make Title, then Model Title * * @return \SquirrelsInventory\Model[] */ public static function getAllModels() { $models = array(); $makes = Make::getAllMakes(); $parents = array(0 => array()); foreach ($makes as $make_id => $make) { $parents[$make_id] = array(); } $query = new \WP_Query(array('post_type' => self::CUSTOM_POST_TYPE, 'post_status' => 'publish', 'posts_per_page' => -1, 'orderby' => 'title', 'order' => 'ASC')); if ($query->have_posts()) { while ($query->have_posts()) { $query->the_post(); $custom = get_post_custom(get_the_ID()); $model = new Model(get_the_ID(), get_the_title()); if (array_key_exists('make_id', $custom)) { $make_id = $custom['make_id'][0]; $model->setMakeId($make_id); if (array_key_exists($model->getMakeId(), $makes)) { $model->setMake($makes[$model->getMakeId()]); } } else { $make_id = 0; } $parents[$make_id][] = $model; } } foreach ($parents as $parent_id => $_models) { /** @var Model[] $_models */ foreach ($_models as $model) { $models[$model->getId()] = $model; } } return $models; }
} /** * Edit a model */ if ($action == 'edit') { // Get ID $id = fRequest::get('id', 'integer'); try { // Get model via ID $m = new Model($id); if (fRequest::isPost()) { // Update model object from POST data and save $m->populate(); $m->store(); // Messaging fMessaging::create('affected', fURL::get(), $m->getId()); fMessaging::create('success', fURL::get(), 'The model ' . $m->getName() . ' was successfully updated.'); fURL::redirect(fURL::get()); } } catch (fNotFoundException $e) { fMessaging::create('error', fURL::get(), 'The model requested, ID ' . $id . ', could not be found.'); fURL::redirect(fURL::get()); } catch (fExpectedException $e) { fMessaging::create('error', fURL::get(), $e->getMessage()); } // Get manufacturers also for drop-down box $manufacturers = fRecordSet::build('Manufacturer', NULL, array('name' => 'asc')); include 'views/models/addedit.php'; } /** * Delete a model
public function scaffold(Model $model, $action = "", $variants = array(), $attrs = null) { $attrs = $this->parseHtmlAttrs($attrs); $result = "<form method=\"post\" action=\"{$action}\"{$attrs}><ol>"; $fields = $model->getAttributes(true); $result .= $this->hidden("id", $model->getId()); foreach ($fields as $name => $type) { if ($variants[$name] === false) { $result .= $this->hidden($name, $model->{$name}); continue; } $label = ucfirst(strtolower(str_replace("_", " ", preg_replace("/([A-Z])/", " \$1", $name)))); switch ($type) { case Model::TYPE_INTEGER: case Model::TYPE_SET: case Model::TYPE_ENUM: if (is_array($variants[$name]) || $variants[$name] instanceof Iterator || $variants[$name] instanceof IteratorAggregate) { $result .= "<li>" . $this->select($name, $variants[$name], $model->{$name}, $label) . "</li>"; } else { $result .= "<li>" . $this->input($name, $model->{$name}, $label, $variants[$name]) . "</li>"; } break; case Model::TYPE_FLOAT: $result .= "<li>" . $this->input($name, $model->{$name}, $label, $variants[$name]) . "</li>"; break; case Model::TYPE_STRING: $result .= "<li>" . $this->input($name, $model->{$name}, $label, $variants[$name], 80) . "</li>"; break; case Model::TYPE_BOOLEAN: $result .= "<li>" . $this->checkbox($name, $model->{$name}, $label) . "</li>"; break; case Model::TYPE_TIMESTAMP: $date = localtime($model->{$name}); $result .= "<li>" . $this->selectDate($name, $model->{$name}, $label, "dmyhs") . "</li>"; break; } } $result .= "<li class=\"reset\"><input type=\"reset\" value=\"Reset\" /></li>"; $result .= "<li class=\"submit\"><input type=\"submit\" value=\"Save\" /></li>"; $result .= "</ol></form>"; return $result; }
/** * @param Model $model * * @return Auto */ public function setModel($model) { $this->model = $model; $this->model_id = $model->getId(); return $this; }
/** * The "U" in CRUD * This could be collapsed under create, for now it's separate for better debugging * It's important to note that edit requires a FileMaker -recid that should be * passed as a hidden form field * * @param Model $model * @param array $fields * @param array $values * @param mixed $conditions * @return array */ function update(&$model, $fields = array(), $values = null, $conditions = null) { // get connection parameters $fm_database = empty($model->fmDatabaseName) ? $this->config['database'] : $model->fmDatabaseName; $fm_layout = empty($model->defaultLayout) ? $this->config['defaultLayout'] : $model->defaultLayout; if (!empty($model->id)) { // set basic connection data $this->connection->SetDBData($fm_database, $fm_layout); // **1 here we remove the primary key field if it's marked as readonly // other fields can be removed by the controller, but cake requires // the primary key to be included in the query if it's to consider // the action an edit foreach ($fields as $index => $field) { if (isset($model->primaryKeyReadOnly) && $field == $model->primaryKey) { unset($fields[$index]); unset($values[$index]); } } // ensure that a recid is passed if (!in_array('-recid', $fields)) { array_push($fields, '-recid'); array_push($values, $model->getId()); } // there must be a -recid field passed in here for the edit to work // could be passed in hidden form field foreach ($fields as $index => $field) { $this->connection->AddDBParam($field, $values[$index]); } // perform edit $return = $this->connection->FMEdit(); if (!$this->handleFXResult($return, $model->name, 'update')) { return FALSE; } if ($return['errorCode'] != 0) { return false; } else { foreach ($return['data'] as $recmodid => $returnedModel) { $recmodid_Ary = explode('.', $recmodid); $model->id = $recmodid_Ary[0]; $model->setInsertID($recmodid_Ary[0]); } return true; } } else { return false; } }
/** * Start with a specific result * * @param int|Model $model The model (or database ID) before the first result * @param bool $inclusive Whether to include the provided model * @param bool $reverse Whether to reverse the results * @return self */ public function startAt($model, $inclusive = false, $reverse = false) { if (!$model) { return $this; } elseif ($model instanceof Model && !$model->isValid()) { return $this; } $this->column($this->sortBy); $this->limited = true; $column = $this->currentColumn; $table = $this->getTable(); $comparison = $this->reverseSort ^ $reverse; $comparison = $comparison ? '>' : '<'; $comparison .= $inclusive ? '=' : ''; $id = $model instanceof Model ? $model->getId() : $model; // Compare an element's timestamp to the timestamp of $model; if it's the // same, perform the comparison using IDs $this->addColumnCondition("{$comparison} (SELECT {$column} FROM {$table} WHERE id = ?) OR ({$column} = (SELECT {$column} FROM {$table} WHERE id = ?) AND id {$comparison} ?)", array($id, $id, $id), 'iii'); return $this; }
/** * Setters */ public function add(Model $model) { $this->models[$model->getId()] = $model; }
/** * Declares an association between this object and a Model object. * * @param Model $v * @return Score The current object (for fluent API support) * @throws PropelException */ public function setModel(Model $v = null) { if ($v === null) { $this->setModelId(NULL); } else { $this->setModelId($v->getId()); } $this->aModel = $v; // Add binding for other direction of this n:n relationship. // If this object has already been added to the Model object, it will not be re-added. if ($v !== null) { $v->addScore($this); } return $this; }
public function editInventory() { if (strlen($_REQUEST['new_make']) > 0 && strlen($_REQUEST['new_model']) > 0) { $make = new Make(); $make->setTitle($_REQUEST['new_make'])->create(); $model = new Model(); $model->setTitle($_REQUEST['new_model'])->setMake($make)->create(); } else { $model = new Model($_REQUEST['model_id']); $model->loadMake(); } $auto = new Auto($_REQUEST['id']); $auto->setPrice($_REQUEST['price'])->setPricePostfix($_REQUEST['price_postfix'])->setTypeId($_REQUEST['type_id'])->setInventoryNumber($_REQUEST['inventory_number'])->setVin($_REQUEST['vin'])->setMakeId($model->getMakeId())->setModelId($model->getId())->setYear($_REQUEST['year'])->setDescription($_REQUEST['description'])->setIsVisible($_REQUEST['is_visible'])->setIsFeatured($_REQUEST['is_featured'])->setInterior($_REQUEST['interior'])->setExterior($_REQUEST['exterior'])->setOdometerReading($_REQUEST['odometer_reading']); /* Features */ $auto->setFeatures(NULL); $features = json_decode(stripslashes($_REQUEST['features']), TRUE); foreach ($features as $f) { if ($f['remove'] == 0) { $feature = new AutoFeature(); $feature->setId(uniqid())->setFeatureId($f['feature_id'])->setFeatureTitle($f['title'])->setValue($f['value'])->setCreatedAt(time())->setUpdatedAt(time()); $auto->addFeature($feature); } } $auto->update(); $images = json_decode(stripslashes($_REQUEST['images']), TRUE); /** Remove deleted images */ if ($auto->getImageCount() > 0) { foreach ($auto->getImages() as $image) { $delete_me = TRUE; foreach ($images as $i) { if ($image->getId() == $i['id']) { $delete_me = FALSE; break; } } if ($delete_me) { $auto->deleteImage($image->getId()); } } } foreach ($images as $i) { /** Add new images */ if ($i['id'] == 0) { $image = new Image(); $image->setInventoryId($auto->getId())->setMediaId($i['media_id'])->setUrl($i['url'])->setIsDefault($i['def'])->create(); $auto->addImage($image); } else { $image = new Image($i['id']); $image->setInventoryId($auto->getId())->setMediaId($i['media_id'])->setUrl($i['url'])->setIsDefault($i['def'])->update(); $auto->setImage($i['id'], $image); } } return $auto->getId(); }
/** * Adds an object to the instance pool. * * Propel keeps cached copies of objects in an instance pool when they are retrieved * from the database. In some cases -- especially when you override doSelect*() * methods in your stub classes -- you may need to explicitly add objects * to the cache in order to ensure that the same objects are always returned by doSelect*() * and retrieveByPK*() calls. * * @param Model $value A Model object. * @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally). */ public static function addInstanceToPool(Model $obj, $key = null) { if (Propel::isInstancePoolingEnabled()) { if ($key === null) { $key = (string) $obj->getId(); } // if key === null self::$instances[$key] = $obj; } }
public function __construct($util, $get = null) { parent::__construct($util); $this->model(); $texte = null; if (isset($get["num"])) { $num = $get["num"]; } else { $num = null; } $rech = false; // si null, vient de menua (menu admin) $model = new Model(); $crypte = new Crypte(); if (!is_null($num)) { //origine=clic un bouton enregistrer ou supprimer if (isset($get["envoi"])) { $enregistrer = $get["envoi"]; } else { $enregistrer = null; } if (!is_null($enregistrer)) { //on a cliqué un bouton envoi switch ($num) { case 1: //vient de la page groupe $nombouton = $get["envoi"]; if ($nombouton == "Enregistrer") { if ($get["nom"] != '' && $get['an'] != '') { if (preg_match("/^[0-9]{2}/", $get["an"])) { $nom = $this->ha($get["nom"]); $an = $this->ha($get["an"]); $parcours = $get["parcours"]; if (!isset($get["numgroupe"])) { //création groupe if ($model->setGroupe($nom, $an, $parcours)) { $texte = 'Groupe créé'; } else { $texte = 'Ce groupe existe déjà'; } } else { //modif groupe $numgroupe = $get["numgroupe"]; $rep = $model->modifGroupe($numgroupe, $nom, $an, $parcours); $texte = 'Groupe modifié'; } } } } if ($nombouton == "Supprimer") { if (isset($get["numgroupe"])) { $numgroupe = $get["numgroupe"]; if ($numgroupe != 0) { $model->delGroupe($numgroupe); $texte = 'Groupe supprimé'; } } } break; case 2: //vient bouton enregistrement prof $nombouton = $get["envoi"]; if ($nombouton == "Enregistrer") { $nom = $this->ha($get["nom"]); $mel = $this->ha($get["mel"]); if ($nom != '' && $mel != '' && $this->ctrlmel($mel)) { $prenom = $this->ha($get["prenom"]); $niveau = $get["niveau"]; if (isset($get["chk"])) { $chk = $get["chk"]; } else { $chk = array(); } if (!isset($get["numprof"])) { //création $res = $model->setProf($nom, $prenom, $mel, $niveau, $crypte->getSmtp(), $crypte->getCrypte()); if ($res) { $numprof = $model->getId(); $model->affecteGroupe($numprof, $chk); } } else { //maj $numprof = $get["numprof"]; if (isset($get["chmdp"])) { $mdp = $this->ha($get["mdp"]); } else { $mdp = null; } $res = $model->modifProf($numprof, $nom, $prenom, $mel, $niveau, $mdp, $crypte->getSmtp(), $crypte->getCrypte()); if ($res) { $model->modifAffecteGroupe($numprof, $chk); } } if ($res) { $texte = 'données enregistrées'; } else { $texte = 'pas d\'enregistrement (doublon)'; } } else { $texte = 'données incorrectes'; } } if ($nombouton == "Supprimer") { $numprof = $get["numprof"]; if (!is_null($numprof)) { if ($numprof != 0) { $model->suppProf($numprof); $texte = 'Professeur supprimé'; } } } break; case 3: //vient bouton enregistrement étudiant $nombouton = $get["envoi"]; if ($nombouton == "Enregistrer") { $nom = $this->ha($get["nom"]); $prenom = $this->ha($get["prenom"]); $mel = $this->ha($get["mel"]); if ($nom != '' && $mel != '' && $this->ctrlmel($mel)) { $groupe = $get["groupe"]; if ($groupe == 0) { $groupe = 'null'; } if (!isset($get["numetud"])) { $res = $model->setEtudiant($nom, $prenom, $mel, $groupe, $crypte->getSmtp(), $crypte->getCrypte()); } else { $numetud = $get["numetud"]; if (isset($get["chmdp"])) { $mdp = $this->ha($get["mdp"]); } else { $mdp = null; } $res = $model->modifEtudiant($numetud, $nom, $prenom, $mel, $groupe, $mdp, $crypte->getSmtp(), $crypte->getCrypte()); } if ($res) { $texte = 'données enregistrées'; } else { $texte = 'pas d\'enregistrement (doublon)'; } } else { $texte = 'données incorrectes'; } } if ($nombouton == "Supprimer") { $numetud = $get["numetud"]; if (!is_null($numetud)) { if ($numetud != 0) { $model->suppEtud($numetud); $texte = 'Étudiant supprimé'; } } } break; case 4: //on vient page recherche objet $rech = true; $nombouton = $get["envoi"]; if ($nombouton == "Rechercher") { $codeobj = $get["groupes"]; if ($codeobj > 0) { $num = 1; } else { $codeobj = $get["professeurs"]; if ($codeobj > 0) { $num = 2; } else { $codeobj = $get["etudiants"]; $num = 3; } } } break; case 5: //on vient page téléversement fichier élève $repfic = 'dirrw/upload/'; $groupe = $get["groupes"]; if ($groupe == 0) { $texte = "choisir le groupe d'affectation"; } else { $texte = ""; if (empty($_FILES['fichier']['name'])) { $texte = "aucun fichier sélectionné"; } else { $tmp = $_FILES['fichier']['tmp_name']; if (!is_uploaded_file($tmp)) { $texte = "fichier non trouvé"; } else { $nf = $_FILES['fichier']['name']; if ($nf != "noms.csv") { $texte = "ce nom de fichier ne convient pas"; } else { if (!move_uploaded_file($tmp, $repfic . $nf)) { $texte = "impossible de copier le fichier"; } else { $texte = "le fichier a été téléversé"; //$nb=$this->enregData($groupe); //on lit le fichier de noms, on les enregistre dans la BD // puis on efface le fichier //on compte le nombre d'erreurs d'enregistrement $flu = fopen("dirrw/upload/noms.csv", "r"); $nb = 0; //nb erreurs while ($ligne = fgetcsv($flu, 140, ";")) { $nom = $ligne[0]; $prenom = $ligne[1]; $mel = $ligne[2]; //tester vraisemblances : à faire pour plus tard... if (!$model->setEtudiant($nom, $prenom, $mel, $groupe, $crypte->getSmtp(), $crypte->getCrypte())) { $nb++; } } fclose($flu); //supprimer fichier unlink("dirrw/upload/noms.csv"); if ($nb == 0) { $texte .= " et les données mises à jour"; } else { $texte .= " mais son contenu n'est pas correct (" . $nb . " problème(s))"; } } } } } } break; } } } else { $num = 1; } $this->setViewMenu(); switch ($num) { case 1: if ($rech) { $data = array("groupe" => $model->getGroupe($codeobj)); } else { $data = array("groupes" => $model->getGroupes()); } break; case 2: if ($rech) { $data = array("professeur" => $model->getProfesseur($codeobj), "groupes" => $model->getGroupesProf($codeobj)); } else { $data = array("groupes" => $model->getGroupes()); } break; case 3: if ($rech) { $data = array("etudiant" => $model->getEtudiant($codeobj), "groupes" => $model->getGroupes()); } else { $data = array("groupes" => $model->getGroupes()); } break; case 4: $data = array("groupes" => $model->getGroupes(), "professeurs" => $model->getProfesseurs(), "etudiants" => $model->getEtudiants()); break; case 5: $data = array("groupes" => $model->getGroupes()); } $data["lng"] = $model->getLng(); $model->close(); $data["param"] = $num; $data["messagetexte"] = $texte; $data["auth"] = $this->util->estAuthent(); $this->view->init('groupe' . $num . '.php', $data); $this->setViewBas(); }