I'm trying to implement https://github.com/zytzagoo/smtp-validate-email for email validation, but I have a problem in the sintallation of the package (manually, I'm not using composer)
So here is the hierarchy of my files:
My index has this code:
<?php
require 'Library/Validator.php';
use \Library\Validator;
$email = 'someone#example.org';
$sender = 'sender#example.org';
$validator = new Validator($email, $sender);
$results = $validator->validate();
var_dump($results);
$log = $validator->getLog();
var_dump($log);
?>
And the 'Validator.php' has 1000 lines of code but here are the first 25 lines so you can have an idea:
<?php
namespace SMTPValidateEmail;
use \SMTPValidateEmail\Exceptions\Exception as Exception;
use \SMTPValidateEmail\Exceptions\Timeout as TimeoutException;
use \SMTPValidateEmail\Exceptions\NoTimeout as NoTimeoutException;
use \SMTPValidateEmail\Exceptions\NoConnection as NoConnectionException;
use \SMTPValidateEmail\Exceptions\UnexpectedResponse as UnexpectedResponseException;
use \SMTPValidateEmail\Exceptions\NoHelo as NoHeloException;
use \SMTPValidateEmail\Exceptions\NoMailFrom as NoMailFromException;
use \SMTPValidateEmail\Exceptions\NoResponse as NoResponseException;
use \SMTPValidateEmail\Exceptions\SendFailed as SendFailedException;
class Validator
{
public $log = [];
/**
* Print stuff as it happens or not
*
* #var bool
*/
public $debug = false;
So, the output of the 'index.php' is this:
Fatal error: Uncaught Error: Class "Library\Validator" not found in C:\xampp\htdocs\EmailValidation\index.php:9 Stack trace: #0 {main} thrown in C:\xampp\htdocs\EmailValidation\index.php on line 9
use namespace name and class name to call it.
use \SMTPValidateEmail\Validator;
example
namespace Helpers
and the CheckUser class
then the text becomes
use Helpers/CheckUser;
Related
I have a Yii1 application and I am trying to debug the application with Xdebug.
The part that I want to debug is a controller action:
<?php
namespace Scrape\controllers;
use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201809\cm\CampaignService;
use Google\AdsApi\AdWords\v201809\cm\OrderBy;
use Google\AdsApi\AdWords\v201809\cm\Paging;
use Google\AdsApi\AdWords\v201809\cm\Selector;
use Google\AdsApi\Common\OAuth2TokenBuilder;
use GuzzleHttp\Client;
use Scrape\domain\creator\IgnoreCreator;
use Scrape\domain\creator\MonitorCreator;
use Scrape\domain\creator\ProjectCreator;
use Scrape\domain\creator\TaskCreator;
use Scrape\domain\deleter\IgnoreDeleter;
use Scrape\domain\deleter\ProjectDeleter;
use Scrape\domain\deleter\ResultDeleter;
use Scrape\domain\deleter\TaskDeleter;
use Scrape\domain\Downloader;
use Scrape\domain\IgnoreFilter;
use Scrape\domain\repository\IgnoreRepository;
use Scrape\domain\repository\ProjectRepository;
use Scrape\domain\repository\ResultRepository;
use Scrape\domain\repository\TaskRepository;
use Scrape\domain\Google;
use Scrape\domain\TaskResetter;
use Scrape\domain\TaskSuggestionRetriever;
use Scrape\models\Ignore;
use Scrape\models\Monitor;
use Scrape\models\Project;
use Scrape\models\Query;
use Scrape\models\Result;
use Scrape\models\Task;
use Scrape\models\TaskIntention;
use Scrape\models\TaskKeywordForm;
use Scrape\models\TaskPopularity;
use Scrape\models\TaskStatus;
use User\models\UserType;
use function GuzzleHttp\Psr7\str;
class DefaultController extends \CController
{
public function actionDownloadTask($id)
{
(new Downloader)->downloadByTask(TaskRepository::findOne($id));
}
public function actionDownloadProject($id)
{
(new Downloader)->downloadByProject(ProjectRepository::findOne($id));
}
}
But I get this error:
Exception has occurred.
Fatal error: Uncaught Error: Class "CController" not found in C:\xampp\htdocs\webScraper\protected\modules\scrape\controllers\DefaultController.php:44
Stack trace:
#0 {main}
thrown
On the class definition.
So my question is: how to tackle this inconvenience?
This is my index.php file:
<?php
use application\components\WebApplication;
define('DIR_ROOT',getcwd().DIRECTORY_SEPARATOR);
$autoload = DIR_ROOT . 'protected/vendor/autoload.php';
$config = DIR_ROOT . 'protected/config/main.php';
$yii = DIR_ROOT . 'protected/components/Yii.php';
// remove the following lines when in production mode
defined('YII_DEBUG') or define('YII_DEBUG',true);
// specify how many levels of call stack should be shown in each log message
defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',3);
require_once($autoload);
require_once($yii);
include DIR_ROOT . 'protected/components/WebApplication.php';
(new WebApplication($config))->run();
As you can see I have $autoload defined in the index.php file. Or do you mean something else?
I am using ampps as a windows 10 apache server, my php version is 7.3. I downloaded it from the LibreOffice download page and installed it on my computer. Then I installed this library via composer https://github.com/ncjoes/office-converter. I try as in the example given, but it does not convert and gives an error. I would be very grateful if you could help me where I am wrong. Here is my code sample and the error I encountered:
<?php
if (!file_exists(__DIR__.'/vendor/autoload.php')) echo 'autoload.php mevcut değil!';
else require __DIR__.'/vendor/autoload.php';
use NcJoes\OfficeConverter\OfficeConverter;
use PHPUnit\Framework\TestCase;
class OfficeConverterTest extends TestCase
{
/**
* #var OfficeConverter $converter
*/
private $converter;
private $outDir;
public function setUp()
{
parent::setUp();
$DS = DIRECTORY_SEPARATOR;
$file = __DIR__."{$DS}sources{$DS}test.docx";
$this->outDir = __DIR__."{$DS}results";
$this->converter = new OfficeConverter($file, $this->outDir);
}
public function testDocxToPdfConversion()
{
$output = $this->converter->convertTo('result.pdf');
$this->assertFileExists($output);
}
public function testDocxToHtmlConversion()
{
$output = $this->converter->convertTo('result.html');
$this->assertFileExists($output);
}
}
$donustur = new OfficeConverterTest();
$donustur->testDocxToPdfConversion();
?>
Fatal error: Uncaught Error: Call to a member function convertTo() on null in C:\Program Files\Ampps\www\converter\converter.php:29 Stack trace: #0 C:\Program Files\Ampps\www\converter\converter.php(43): OfficeConverterTest->testDocxToPdfConversion() #1 {main} thrown in C:\Program Files\Ampps\www\converter\converter.php on line 29
When running tests, we are supposed to leave running them to phpunit, but you are trying to call manually (in last 2 lines of your code).
But if you insist on calling manually, change:
$donustur = new OfficeConverterTest();
$donustur->testDocxToPdfConversion();
Into:
$donustur = new OfficeConverterTest();
$donustur->setUp();
$donustur->testDocxToPdfConversion();
So that you call setUp() which phpunit would normally call for you automatically.
See also:
How do I run all my PHPUnit tests?
How to run single test method with phpunit?
Example for page
If you want to use this logic on a Web-Page, it should look something like:
<?php
if (!file_exists(__DIR__.'/vendor/autoload.php')) echo 'autoload.php mevcut değil!';
else require __DIR__.'/vendor/autoload.php';
use NcJoes\OfficeConverter\OfficeConverter;
echo 'Converting...<br>';
$input = __DIR__ . '/test.docx';
$converter = new OfficeConverter($input, __DIR__.'/results');
$output = $converter->convertTo('result.pdf');
echo 'Saved at:' . $output . '<br>';
I am writing a program which processes geographical coordinates of a city and I want to randomly select my city in each run; the process for all cities are the same.
I have a PHP class for each city which contains geographical coordinates of it; for example:
<?php
namespace Utility\Locations;
class Tehran
{
const MIN_LAT = 35.325;
const MAX_LAT = 35.390;
const MIN_LNG = 51.165;
const MAX_LNG = 51.230;
}
In another PHP file I make use of the class as:
use Utility\Locations\Tehran;
use Utility\Locations\Karaj;
...
protected function MyProcessingMethod () {
...
$city = Faker::create()->randomElement(array("Tehran", "Karaj"));
echo $city::MIN_LAT;
...
}
...
If it helps, the above mentioned file is a CodeCeption Cest and MyProcessingMethod is used as a DataProvider. When I run my tests using codecept run scenarios/MyCest.php, I get this error:
PHP Fatal error: Uncaught Error: Class 'Tehran' not found in /home/zeinab/PhpstormProjects/test/scenarios/MyCest.php:190
Stack trace:
#0 [internal function]: MyCest->MyProcessingMethod()
#1 /home/zeinab/PhpstormProjects/test/vendor/codeception/codeception/src/Codeception/Util/ReflectionHelper.php(47): ReflectionMethod->invokeArgs(Object(MyCest), Array)
#2 /home/zeinab/PhpstormProjects/test/vendor/codeception/codeception/src/Codeception/Test/Loader/Cest.php(65): Codeception\Util\ReflectionHelper::invokePrivateMethod(Object(MyCest), Object(ReflectionMethod))
#3 /home/zeinab/PhpstormProjects/test/vendor/codeception/codeception/src/Codeception/Test/Loader.php(109): Codeception\Test\Loader\Cest->loadTests('/home/zeinab/Ph...')
#4 /home/zeinab/PhpstormPro in /home/zeinab/PhpstormProjects/test/scenarios/MyCest.php on line 190
I've read PHP official documentations on this type of usage, but all examples there were using the classes that are defined inside destination file.
I also tried this:
$city = Faker::create()->randomElement(array(Tehran::class, Karaj::class));
echo $city::MIN_LAT;
But I got the same error.
Is there anyway to do what I want to?
EDIT 1:
I have put the path to the classes in psr-4 tag of my composer.json:
"autoload": {
"psr-4": {
"Utility\\": "Utility/"
}
}
It seems there is no problem in loading the classes, since using them directly works fine. For example the following code is doing great:
echo Tehran::MIN_LAT;
I created this code snippet for example purposes - so it may not fully reflect your methods but the answer is the principle :)
<?php
# create our city classes
class Brighton
{
const X = 1;
const Y = 2;
}
class London
{
const X = 3;
const Y = 4;
}
# create our get city class
class Foo
{
public function getCity()
{
$possibleCities = ['Brighton', 'London', 'Birmingham']; # add a city that's not a class for testing
$city = rand(0, count($possibleCities) -1);
return $possibleCities[$city];
}
}
# init foo
$foo = new Foo();
$city = $foo->getCity(); # get city
# check if class exists, if it does, init it
$cityClass = (class_exists($city) ? new $city() : null);
# check if class is empty - if it isn't echo CONST X
echo (!empty($cityClass) ? $cityClass::X : $city. ' class not found');
How to include the classes (if they're in separate files):
Imagine the tree is:
|-app
|-----core
|---------city
|-------------Brighton.php
|-------------London.php
|-----Foo.php
In Foo.php
<?php
require_once 'city/Brighton.php';
require_once 'city/London.php';
use City\Brighton;
use City\London;
# etc. etc
And then Brighton.php and London.php have the namespace of City:
<?php
namespace City;
class Brighton
{} # etc
add loader to first line of your code :
function loader($className)
{
$fileName = str_replace('\\', '/', $className) . '.php';
require_once $fileName;
}
spl_autoload_register('loader');
then use namespaces like directory structures :
Ahvaz.php in app/core/city directory
namespace app\core\city;
class Ahvaz
{
//...
}
when you load a class Ahvaz.php like this
$var = new Ahvaz();
you need to add use app\core\city;
then you have :
use app\core\city;
$var = new Ahvaz();
it will include Ahvaz.php from app/core/city directory
I'm using Laravel 5.2 & PHP Version 5.6.21 and have come across the issue :
FatalErrorException in Log.php line 8: Cannot declare class
App\Utils\System\Log because the name is already in use
in Log.php line 8
My Log.php looks like this :
<?php namespace App\Utils\System;
use Log;
use App\Log as LogDB;
use Carbon\Carbon as Carbon;
class Log
{
public function save($msg,$flag)
{
/*
//check to see if there is an organisation set
$org = '';
if(!is_null(session('organisation_name')))
{
$org = session('organisation_name');
}
$message ='{"action":"'.$msg.'", "uuid":"'.\Auth::user()->id.'", "company_id":"'.\Auth::user()->company_id.'","Organisation":"'.$org.'","Date":"'.Carbon::now().'"}';
//set a local log
if($flag=='info')
Log::info($message);
//save to the DB
$l = new LogDB();
$l->log_message = $message;
$l->save();
*/
}
}
The problem, I'm finding is, If I rename log to anything else, I always get the error...
Has anyone had this issue? Any fixes known.
Thanks
I get a problem when I use the SOAP component in zend framework 2.0
The following is the code :
namespace User\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Soap\Server;
use Zend\Soap\Client;
use Zend\Soap\AutoDiscover;
use User\Model\MyTest;
class TestController extends AbstractActionController {
private $_WSDL_URI = "http://127.0.0.1/test/index?wsdl";
private function handleWSDL() {
$autodiscover = new AutoDiscover();
//ini_set("soap.wsdl_cache_enabled", 0);
$autodiscover->setClass('User\Model\MyTest')
->setUri($this->_WSDL_URI);
$wsdl = $autodiscover->generate();
header("Content-type: text/xml");
echo $wsdl->toXml();
exit;
}
private function handleSOAP() {
$soap = new Server($this->_WSDL_URI,array('encoding' => 'utf-8','soap_version'=>SOAP_1_2));
$soap->setClass('User\Model\MyTest');
$soap->handle();
exit;
}
public function indexAction(){
if(isset($_GET['wsdl'])) {
$this->handleWSDL();
} else {
$this->handleSOAP();
}
}
public function clientAction(){
$client = new Client('http://127.0.0.1/test/index?wsdl');
$result = $client->getUser(31);
var_dump($result);exit;
}
}
when I visit http://localhost/test/index?wsdl ,It returns the WSDL.
But when I visit http://localhost/test/index,It returns the error:
SOAP-ERROR: Parsing WSDL: Couldn't load from http://127.0.0.1/test/index?wsdl : failed to load external entity "http://127.0.0.1/test/index?wsdl"
When I visit http://localhost/test/client, It returns
An error occurred
An error occurred during execution; please try again later.
Additional information:
SoapFault
File:
E:\WWW\vendor\ZF2\library\Zend\Soap\Client.php:1087
Message:
Wrong Version
Stack trace:
#0 E:\WWW\vendor\ZF2\library\Zend\Soap\Client.php(1087): SoapClient->__soapCall('getUser', Array, NULL, NULL, Array)
#1 E:\WWW\module\User\src\User\Controller\TestController.php(44): Zend\Soap\Client->__call('getUser', Array)
here is the MyTest.php file
namespace User\Model;
class MyTest{
/**
* To get the register information of the user
*
* #return string
*/
public function getUser(){
return 'hello';
}
}
Thanks in advance.
To create a Soap server, you only need the WSDL file, not the URL that is used to serve it to other clients. In fact, it is better performing NOT to use a URL for this, because every request to the Soap server will start a subrequest to fetch the WSDL.
Try to put the WSDL somewhere once it's created, and fetch it from there on subsequent requests. Autodetecting it every time is only good when doing development without a specified interface. Which will break things once somebody else is using this interface and relies on its stability.