<?php require_once 'Calculator.php'; $calculator = new Calculator(); //var_dump(range(1,100)); $calculator->run('+', range(1, 100)); echo $calculator; var_dump('--------- run +1'); $calculator->run('+', [1]); echo $calculator; var_dump('--------- run *2'); $calculator->run('*', [2]); echo $calculator; var_dump('--------- reset'); $calculator->reset(); echo $calculator; var_dump('--------- new add'); $calculator->run('+', [1, 100]); echo $calculator;
public function actionIndex() { $personForm = new PersonForm(); $eventForm = new EventForm(); $person = null; $event = null; $tplData = array('personForm' => $personForm, 'eventForm' => $eventForm); if (($personFormData = Yii::app()->getRequest()->getPost('PersonForm')) !== null) { $personForm->setAttributes($personFormData); //var_dump($personForm); if ($personForm->validate()) { $person = new Person(); $person->setAttributes(array('name' => $personForm->name, 'gender' => $personForm->gender, 'date' => $personForm->date, 'time' => $personForm->getTime(), 'city_id' => $personForm->city_id)); /* if($person->validate()) { $calculator = new Calculator($person); // Запуск расчета $calculator->run(); $this->calculator = $calculator; //var_dump($calculator->chart); //$tplData['calculator'] = $calculator; } else { $personForm->addErrors($person->getErrors()); } * */ } } if (($eventFormData = Yii::app()->getRequest()->getPost('EventForm')) !== null) { $eventForm->setAttributes($eventFormData); if ($eventForm->date != '' || $eventForm->city_id != '' || $eventForm->hour != '' || $eventForm->minute != '') { //var_dump($personForm); if ($eventForm->validate()) { $event = new Event(); $event->setAttributes(array('date' => $eventForm->date, 'time' => $eventForm->getTime(), 'city_id' => $eventForm->city_id)); } } } if ($person !== null) { $validateResult = $person->validate(); $validateResult = $validateResult && ($event !== null ? $event->validate() : true); } if ($validateResult) { $calculator = new Calculator($person, $event); // Запуск расчета $calculator->run(); $this->calculator = $calculator; //var_dump($calculator->chart); //$tplData['calculator'] = $calculator; } else { if ($person !== null) { $personForm->addErrors($person->getErrors()); } if ($event !== null) { $eventForm->addErrors($event->getErrors()); } } // Вывод в шаблон $this->render('index', $tplData); }
echo $file; ?> "><?php echo $file; ?> </a></li> <?php } ?> </ul> <?php } else { try { $app = new Calculator($param); $data = $app->run(); ?> <h2>Výsledky mého počítání</h2> <h3>Daně</h3> <table> <tr> <th>Příjmy:</th> <td><?php echo $tpl->currency($data['income']); ?> </td> </tr> <tr> <th>Výdaje:</th>
<?php require_once 'Calculator.php'; $calculator = new Calculator(); var_dump('/* ------ Add -------- */'); $calculator->run('+', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]); echo $calculator; var_dump('/* ------ Add -------- */'); $calculator->reset(); // variable de classe $result $calculator->run('+', range(1, 100)); echo $calculator; var_dump('/* ------ Mul -------- */'); $calculator->reset(); // variable de classe $result $calculator->run('*', range(1, 5)); echo $calculator; var_dump('/* ------ test -------- */'); $calculator->reset(); $calculator->run('+', []); echo $calculator; var_dump('/* ------ test -------- */'); $calculator->reset(); $calculator->run('*', []); echo $calculator; var_dump('/* ------ test foo -------- */'); $calculator->reset(); $calculator->run('*', 'foo'); echo $calculator;
<?php /* * * This is a simpel php oop calculator, hope it will be * of use, enjoy and happy coding. * */ require_once 'calculator.php'; $cal = new Calculator(); $cal->run(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" charset="UTF-8" content="width=device-width, initial-scale=1"> <title>Calculator</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"> <style> body{ background-color: #222; } .max-960{ max-width: 960px; margin: 0 auto; }
/** * Запускаем отрисовку виджета * * @return void */ public function run() { // Авторизован ли пользователь if (Yii::app()->user->isAuthenticated() === false) { return; } if (($user = Yii::app()->user->getProfile()) === null) { return; } // Загрузка таблицы для блока $table = Table::model()->with(array('descriptions'))->findByPK((int) $this->model_id); if ($table === null) { return; } // Устанавливаем источники данных $person = null; $event = null; $personForm = new PersonForm(); $eventForm = new EventForm(); $description = ''; if ($table->source_destiny_table == Table::SOURCE_USER) { $person = new Person(); $person->setAttributes(array('name' => $user->profile->name, 'gender' => $user->profile->gender, 'date' => $user->profile->birth_date, 'time' => $user->profile->birth_time, 'city_id' => $user->profile->city_id)); } elseif ($table->source_destiny_table == Table::SOURCE_ADMIN) { $person = $table->person; } elseif ($table->source_destiny_table == Table::SOURCE_FROM_USER && ($personFormData = Yii::app()->getRequest()->getPost('PersonForm')) !== null) { $personForm->setAttributes($personFormData); if ($personForm->validate()) { $person = new Person(); $person->setAttributes(array('name' => $personForm->name, 'gender' => $personForm->gender, 'date' => $personForm->date, 'time' => $personForm->getTime(), 'city_id' => $personForm->city_id)); } } if ($table->source_event_table == Table::SOURCE_USER) { $event = new Event(); $event->setAttributes(array('date' => date('Y-m-d'), 'time' => date('H:i'), 'city_id' => $user->profile->city_id)); } elseif ($table->source_event_table == Table::SOURCE_ADMIN) { $event = $table->event; } elseif ($table->source_event_table == Table::SOURCE_FROM_USER && ($eventFormData = Yii::app()->getRequest()->getPost('EventForm')) !== null) { $eventForm->setAttributes($eventFormData); if ($eventForm->date != '' || $eventForm->city_id != '' || $eventForm->hour != '' || $eventForm->minute != '') { if ($eventForm->validate()) { $event = new Event(); $event->setAttributes(array('date' => $eventForm->date, 'time' => $eventForm->getTime(), 'city_id' => $eventForm->city_id)); } } } if ($person !== null) { $validateResult = $person->validate(); $validateResult = $validateResult && ($event !== null ? $event->validate() : true); } if ($validateResult) { $calculator = new Calculator($person, $event); // Запуск расчета $calculator->run(); if ($table->active_luck_pillar > 0) { $calculator->numCurrentLuckColumn = (int) $table->active_luck_pillar; } // Определяем описание $description = $table->description; } else { if ($person !== null) { $personForm->addErrors($person->getErrors()); } if ($event !== null) { $eventForm->addErrors($event->getErrors()); } } if (Yii::app()->request->isAjaxRequest) { $this->controller->renderPartial('//bazi/widgets/TableWidget/_chart', array('model' => $table, 'calculator' => $calculator, 'description' => $description), false, true); } else { $this->render($this->view, array('model' => $table, 'calculator' => $calculator, 'description' => $description, 'personForm' => $personForm, 'eventForm' => $eventForm)); } }
/** * Запускаем отрисовку виджета * * @return void */ public function run() { // Авторизован ли пользователь if (Yii::app()->user->isAuthenticated() === false) { return; } if (($user = Yii::app()->user->getProfile()) === null) { return; } // Загрузка таблицы для блока $table = Table::model()->with(array('markup'))->findByPK((int) $this->model_id); if ($table === null) { return; } // Генерируем уникальный код таблицы $tableCode = $this->block_id !== null ? $this->block_id . '-' : ''; $tableCode .= $table->id . '-' . mt_rand(100000, 999999); // Устанавливаем источники данных $personForm = new PersonForm(); $eventForm = new EventForm(); $beforeDescription = ''; $afterDescription = ''; $useAltTable = false; // Если Персона не установлена if ($this->person === null) { // Если источник данных - данные пользователя, // то берем все данные из профиля пользователя if ($table->source_destiny_table == Table::SOURCE_USER) { $this->person = new Person(); $this->person->setAttributes(array('name' => $user->profile->name, 'gender' => $user->profile->gender, 'date' => $user->profile->birth_date, 'time' => $user->profile->birth_time, 'city_id' => $user->profile->city_id)); } elseif ($table->source_destiny_table == Table::SOURCE_ADMIN) { $this->person = $table->person; } } // Если Событие не установлено if ($this->event === null) { // Если источник данных - данные от администратора, // то берем данные из БД if ($table->source_event_table == Table::SOURCE_ADMIN) { $this->event = $table->event; } } // Проверка данных if ($this->person !== null) { $validateResult = $this->person->validate(); $validateResult = $validateResult && ($this->event !== null ? $this->event->validate() : true); } // Если данные корректны if ($validateResult) { // Создаем калькулятор $calculator = new Calculator($this->person, $this->event); // Определяем активный столп if ($table->active_luck_pillar > 0) { $calculator->numCurrentLuckColumn = (int) $table->active_luck_pillar; } // Запуск расчета $calculator->run(); // Если задана разметка, запускаем анализаторы if (!empty($table->markup)) { // Анализатор $analyzer = new Analyzer($calculator); // Запуск анализа $analyzer->run(); $markupAnalyzer = new MarkupAnalyzer($table, $analyzer); $markupAnalyzer->run(); //var_dump($markupAnalyzer->getFoundedMarkupItems()); //exit(); // Найденные элементы разметки $foundedMarkupItems = $markupAnalyzer->getFoundedMarkupItems(); $useIndividualDescription = false; // Если не найден ни один элемент разметки if (empty($foundedMarkupItems)) { // Если используется альтернативная таблица if ($table->source_destiny_table == Table::SOURCE_USER && $table->use_alt_table) { // Используем альтернативную таблицу // Создаем калькулятор $calculator = new Calculator($table->altTable, $this->event); // Определяем активный столп if ($table->active_luck_pillar > 0) { $calculator->numCurrentLuckColumn = (int) $table->active_luck_pillar; } // Запуск расчета $calculator->run(); // Анализатор $analyzer = new Analyzer($calculator); $analyzer->run(); $markupAnalyzer = new MarkupAnalyzer($table, $analyzer); $markupAnalyzer->run(); // Альтернативное описание if ($table->description_place == Table::DESCRIPTION_PLACE_BEFORE) { $beforeDescription = $table->alt_description; } elseif ($table->description_place == Table::DESCRIPTION_PLACE_AFTER) { $afterDescription = $table->alt_description; } $useAltTable = true; } else { // В противном случае выводим основное описание if ($table->description_place == Table::DESCRIPTION_PLACE_BEFORE) { $beforeDescription = $table->description; } elseif ($table->description_place == Table::DESCRIPTION_PLACE_AFTER) { $afterDescription = $table->description; } } } else { $useIndividualDescription = true; } if ($useIndividualDescription) { // Формируем описания до таблиц и после для каждой найденной разметки foreach ($foundedMarkupItems as $markupItem) { if ($markupItem->description_place == TableMarkup::DESCRIPTION_PLACE_BEFORE) { // Общее описание $beforeDescription .= $markupItem->description; // Описание для женщины $beforeDescription .= $this->person->gender == Person::GENDER_FEMALE && $markupItem->description_f != '' ? $markupItem->description_f : ''; // Описание для мужчины $beforeDescription .= $this->person->gender == Person::GENDER_MALE && $markupItem->description_m != '' ? $markupItem->description_m : ''; } elseif ($markupItem->description_place == TableMarkup::DESCRIPTION_PLACE_AFTER) { // Общее описание $afterDescription .= $markupItem->description; // Описание для женщины $afterDescription .= $this->person->gender == Person::GENDER_FEMALE && $markupItem->description_f != '' ? $markupItem->description_f : ''; // Описание для мужчины $afterDescription .= $this->person->gender == Person::GENDER_MALE && $markupItem->description_m != '' ? $markupItem->description_m : ''; } } } } } else { // Формируем список ошибок $errors = array(); if ($this->person !== null) { foreach ($this->person->getErrors() as $key => $error) { $errors['Person'][$key] = $error; } } if ($this->event !== null) { foreach ($this->event->getErrors() as $key => $error) { $errors['Event'][$key] = $error; } } } //var_dump($beforeDescription); // Вывод в шаблон if (Yii::app()->request->isAjaxRequest) { // Если аякс-запрос, то перерисовываем только чарт $this->controller->renderPartial('//bazi/widgets/TableWidget/_chart', array('model' => $table, 'tableCode' => $tableCode, 'calculator' => $calculator, 'beforeDescription' => $beforeDescription, 'afterDescription' => $afterDescription, 'useAltTable' => $useAltTable, 'markupCells' => isset($markupAnalyzer) ? $markupAnalyzer->getMarkupCells() : array(), 'markupRelations' => isset($markupAnalyzer) ? $markupAnalyzer->getMarkupRelations() : array())); } else { $this->render($this->view, array('model' => $table, 'tableCode' => $tableCode, 'calculator' => $calculator, 'beforeDescription' => $beforeDescription, 'afterDescription' => $afterDescription, 'useAltTable' => $useAltTable, 'personForm' => $personForm, 'eventForm' => $eventForm, 'errors' => $errors, 'markupCells' => isset($markupAnalyzer) ? $markupAnalyzer->getMarkupCells() : array(), 'markupRelations' => isset($markupAnalyzer) ? $markupAnalyzer->getMarkupRelations() : array())); } }
<?php namespace Calculator; include __DIR__ . '/autoloader.php'; $calculator = new Calculator(new Input(), new Output()); $calculator->addOperation(new AddOperation()); $calculator->addOperation(new MinusOperation()); $calculator->addOperation(new TimesOperation()); $calculator->addOperation(new DivideOperation()); $calculator->addOperation(new ModulusOperation()); $calculator->addOperation(new PowerOperation()); $calculator->addFunction(new RoundFunction()); $calculator->addFunction(new SqrtFunction()); $calculator->run();